Escape Sequences
Some characters, such as backspace or control characters, have no visible image. Such characters are nonprintable. Other characters (single and double quotation marks, question mark, and backslash) have special meaning in the language. Our programs cannot use any of these characters directly. Instead, we use an escape sequence to represent such characters. An escape sequence begins with a backslash. The language defines several escape sequences:
- newline \n horizontal tab \t alert (bell) \a
- vertical tab \v backspace \b double quote \"
- backslash \\ question mark \ single quote \’
- carriage return \r formfeed \f
We use an escape sequence as if it were a single character:
- std::cout << ’\n’;
- std::cout << "\tHi!\n";
We can also write a generalized escape sequence, which is \x followed by one or more hexadecimal digits or a \ followed by one, two, or three octal digits. The value represents the numerical value of the character. Some examples (assuming the Latin-1 character set):
- \7 (bell) \12 (newline) \40(blank)
- \0 (null) \115 (’M’) \x4d (’M’)
As with an escape sequence defined by the language, we use these escape sequences as we would any other character:
- std::cout << "Hi \x4dO\115!\n";
- std::cout << ’\115’ << ’\n’;
Note that if a \ is followed by more than three octal digits, only the first three are associated with the \. For example, "\1234" represents two characters: the character represented by the octal value 123 and the character 4. In contrast, \x uses up all the hex digits following it; "\x1234" represents a single, 16-bit character composed from the bits corresponding to these four hexadecimal digits. Because most machines have 8-bit chars, such values are unlikely to be useful. Ordinarily, hexadecimal characters with more than 8 bits are used with extended characters sets using one of the prefixes from Table 2.2.
Specifying the Type of a Literal
We can override the default type of an integer, floating- point, or character literal by supplying a suffix or prefix as listed in Table 2.2.
- L’a’
- u8"hi!"
- 42ULL
- 1E-3F
- 3.14159L