String literals
A string literal contains a sequence
of characters or escape sequences enclosed in double quotation mark
symbols. A string literal with the prefix L
is a wide
string literal. A string literal without the prefix L
is
an ordinary or narrow string literal.
The
type of narrow string literal is array of
char
. The
type of a wide character string literal is array of wchar_t
Both
types have static storage duration.
The type of a narrow string literal is array
of
const char
. The type of a wide string literal
is array of const wchar_t
. Both types have static
storage duration.
String literal syntax
Multiple spaces contained within a string literal are retained.
Use the escape sequence \n
to
represent a new-line character as part of the string. Use the escape
sequence \\
to represent a backslash character as
part of the string. You can represent a single quotation mark symbol
either by itself or with the escape sequence \'
.
You must use the escape sequence \"
to represent
a double quotation mark.
Outside of the basic source character
set, the universal character names for letters and digits are allowed in C++ and at the C99 language level. In C++, you must compile with the LANGLVL(UCS) option
for universal character name support.
char titles[ ] = "Handel's \"Water Music\"";
char *temp_string = "abc" "def" "ghi"; // *temp_string = "abcdefghi\0"
wchar_t *wide_string = L"longstring";
This example illustrates escape sequences in string literals:
CCNX02K
#include <iostream> using namespace std;
int main () {
char *s ="Hi there! \n";
cout << s;
char *p = "The backslash character \\.";
cout << p << endl;
char *q = "The double quotation mark \".\n";
cout << q ;
}
This program produces the following output: Hi there! The backslash character \. The double quotation mark ".
\
symbol) followed by optional whitespace and a
new-line character (required). For example: char *mail_addr = "Last Name First Name MI Street Address \
893 City Province Postal code ";
String concatenation
"hello " "there" //equivalent to "hello there"
"hello" "there" //equivalent to "hellothere"
Characters
in concatenated strings remain distinct. For example, the strings "\xab"
and "3"
are
concatenated to form "\xab3"
. However, the characters \xab
and 3
remain
distinct and are not merged to form the hexadecimal character \xab3
.
"hello " L"there"
the
result is a wide string literal.



char
is
appended at the end of each string. For a wide string literal, '\0' of
type wchar_t
is appended. By convention, programs
recognize the end of a string by finding the null character. For
example: char *first = "Hello "; //stored as "Hello \0"
char *second = "there"; //stored as "there\0"
char *third = "Hello " "there"; //stored as "Hello there\0"