Character Types
Lesson outline
Working with Characters
The char type stores a single character code unit. sizeof(char) is 1 byte by definition, and a byte is at least 8 bits (CHAR_BIT ≥ 8).
Character literals are enclosed in single quotes (e.g., 'A', '9', '$') and may include escape sequences such as '\n' for newline.
The exact narrow character encoding (ASCII, UTF-8, etc.) is implementation-defined; don't assume ASCII everywhere.
Character Examples
Examples of declaring and printing characters:
Escape Sequences
Common escapes include \n (newline), \t (tab), \a (bell), \' (single quote), \" (double quote), and \\ (backslash). You can also use hexadecimal (\x41) or octal (\101) escapes.
Encodings and ASCII
Many platforms use ASCII or a superset (like UTF-8) for the narrow execution character set, but the C++ standard does not require ASCII.
If you rely on numeric codes, prefer readable escape sequences (e.g., '\n' instead of 10).
In ASCII specifically, codes 0 - 31 are control characters and 32 - 126 are printable.
Signedness and <cctype> Functions
char may be signed or unsigned depending on the implementation. When passing a char to classification functions like std::isalpha, cast to unsigned char to avoid undefined behavior for negative values.
Unicode and Wider Character Types
For Unicode text, prefer std::string (commonly UTF-8) or wider character types when appropriate:
char8_t(C++20) for UTF-8 literals:u8"…"char16_t/char32_tfor UTF-16/UTF-32:u"…",U"…"wchar_tis implementation-defined width and encoding
Remember that a char stores a code unit, not necessarily a complete user-visible character (grapheme).