By Stephen R. Davis

In C++, you can code a normal, printable character by placing it in single quotes: char cSpace = ‘ ‘;. You can code any character you want, whether printable or not, by placing its octal value after a backslash: char cSpace = ‘40’;.

A constant that appears with a leading zero is assumed to be octal (that is, base 8).

You can code characters in base 16, also called hexadecimal, by preceding the number with a backslash followed by a small x as in the following example:

char cSpace = 'x20';

The decimal value 32 is equal to 40 in base 8 and 20 in base 16. Don’t worry if you don’t feel comfortable with octal or hexadecimal just yet. C++ provides shortcuts for the most common characters.

C++ provides names for some of the unprintable characters that are particularly useful. Some of the more common ones are shown in the table.

Some of the Special C++ Characters
Char Special Symbol Char Special Symbol
Newline n
Carriage Return r
\ Tab t
NULL Bell a

The most common is the newline character, which is nicknamed ‘n’. In addition, you must use the backslash if you want to print the single-quote character:

char cQuote = ''';

Because C++ normally interprets a single quotation mark as enclosing a character, you have to precede a single quote mark with a backslash character to tell it, “Hey, this single quote isn’t enclosing a character, it is the character.”

In addition, the character ‘\’ is a single backslash.

This leads to one of the more unfortunate coincidences in C++. In Windows, the backslash is used in filename paths, as in the following:

C:\Base DirectorySubdirectoryFile Name

This is encoded in C++ with each backslash replaced by a pair of backslashes, as follows:

"C:\\Base Directory\Subdirectory\File Name"