Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 171 Β· Variables and Types

Characters and Booleans

Learn how C++ char really works (a small integer, signed or not), ASCII arithmetic, <cctype> pitfalls, char8_t/char16_t/char32_t, and bool conversions.

Two of C++'s fundamental types look almost too simple to need a lesson: char holds a character and bool holds true or false. Underneath, both are small integers, and that fact explains everything that surprises people about them: why 'A' + 1 is 66, why std::toupper can print a number, why a char might be negative, and why if (count == true) can be false even when count is 2.

This lesson covers char and character codes, the <cctype> helpers and their one important rule, the Unicode character types, and how bool converts to and from everything else.

char is a number with a character costume

A char is exactly one byte. What it stores is a number, a character code. When you write 'A' in single quotes, you get the code of the letter A in the execution character set, which on every platform you will meet is ASCII-compatible: 'A' is 65, 'a' is 97, '0' is 48, and a space is 32.

Whether you see a letter or a number depends on how you print it:

C++ Characters are numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line is worth understanding. In letter + 1, the char is promoted to int before the addition (all arithmetic on small types happens in at least int), so the result is the int 66 and prints as a number. Storing it back into a char, as next does, makes it a character again.

Two tricks from that program are used constantly:

  • ch - '0' turns a digit character into its value: '7' - '0' is 7. This works because the standard guarantees '0' to '9' have consecutive codes.
  • ch - 'a' gives a letter's position in the alphabet, handy for counting letters. Letters being consecutive is true for ASCII, but not guaranteed by the standard (old IBM EBCDIC systems differ), which is one reason to prefer <cctype> functions where they fit.

A slice of the ASCII table

Codes Characters
0–31 control characters: '\0' (0), '\t' (9), '\n' (10), '\r' (13)
32 space
48–57 '0' to '9'
65–90 'A' to 'Z'
97–122 'a' to 'z'
127 DEL (control)

ASCII only defines codes 0–127. Lowercase letters are exactly 32 above their uppercase partners, a difference of one bit, but please use std::toupper rather than bit tricks.

Escape sequences

Characters you can't type directly use escapes, the same ones you met in Printing Output: '\n' (newline), '\t' (tab), '\\' (backslash), '\'' (single quote), '\"' (double quote), '\0' (the null character, code 0), and numeric forms like '\x41' (hex, 'A') or '\101' (octal, also 'A').

Is char signed? It depends

C++ has three distinct one-byte character types: char, signed char and unsigned char. Plain char has the same range as one of the other two, but which one is implementation-defined:

  • On x86 and x86-64 (Windows, Linux, macOS on Intel), char is signed: βˆ’128 to 127.
  • On ARM Linux and Android, and on PowerPC, char is unsigned: 0 to 255. (Apple's ARM platforms keep it signed.)

For text in ASCII that never matters. It matters as soon as you store bytes above 127, which happens with every non-English character in UTF-8:

C++ When char goes negative

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The two bytes of Γ© print as negative numbers when read through a signed char. If your code uses a char as an array index, a lookup key, or a <cctype> argument, a negative value is a bug. The fix is always the same: convert to unsigned char first whenever you treat a char as a number. And when you mean raw bytes rather than text, use unsigned char, std::uint8_t or std::byte (C++17), never plain char.

The <cctype> functions

The <cctype> header classifies and converts single characters:

Function True for / does
std::isalpha(c) letters
std::isdigit(c) '0'–'9'
std::isalnum(c) letters or digits
std::isspace(c) space, \t, \n, \v, \f, \r
std::isupper(c), std::islower(c) uppercase / lowercase letters
std::ispunct(c) punctuation
std::toupper(c), std::tolower(c) converted letter (other characters unchanged)

They come from C, and that shows in two ways. First, they take and return int, and the classification functions return "nonzero" rather than true. Second, passing a negative value other than EOF is undefined behavior, and plain char is negative for non-ASCII bytes on most desktops. So wrap them:

C++ Using cctype correctly

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

These functions only understand single bytes in the current C locale, which is plain ASCII by default. std::toupper can't uppercase Γ© stored as two UTF-8 bytes, let alone handle German ß β†’ SS. Real Unicode text processing needs a library such as ICU. For identifiers, commands and other ASCII data, <cctype> is fine.

Wide and Unicode character types

Besides char, C++ has character types for wider encodings. You'll see them in Windows APIs, file formats and text libraries:

Type Literal Holds
wchar_t L'x', L"text" a "wide" character: 16 bits (UTF-16) on Windows, 32 bits on Linux and macOS
char8_t (C++20) u8'x', u8"text" a UTF-8 code unit
char16_t u'x', u"text" a UTF-16 code unit
char32_t U'x', U"text" a UTF-32 code unit, which is one whole Unicode code point
C++
char32_t smile = U'πŸ˜€';             // one code point: U+1F600
std::u8string greeting = u8"hΓ©llo"; // std::basic_string<char8_t>
std::u16string title = u"Straße";   // UTF-16 code units

A few honest notes:

  • In practice, most modern C++ code stores UTF-8 in ordinary std::string. GCC and Clang treat source files and string literals as UTF-8 by default, and MSVC does with the /utf-8 flag. That is what the "cafΓ©" example above relies on.
  • C++20 changed u8"..." literals from char to char8_t, which broke some older code. std::println and std::cout can't print char8_t, char16_t or char32_t strings directly.
  • One char32_t is one code point, but even that is not always one "character" on screen: emoji with skin tones or flags combine several code points.

Unless an API demands one of these types, use std::string with UTF-8.

bool: true, false and conversions

A bool holds true or false. Comparisons (==, <, …) and logical operators (&&, ||, !, covered in Comparison and Logical Operators) produce bool values. std::println prints them as words, while std::cout prints 1 and 0 unless you ask for std::boolalpha.

Conversions happen in both directions, automatically:

  • To bool: zero (0, 0.0, '\0') and null pointers become false. Every other value becomes true, including -1 and 0.5.
  • From bool: true becomes 1 and false becomes 0 in arithmetic.
C++ bool conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last two lines show a real bug pattern. if (items) asks "is it nonzero?", which is true. items == true converts true to the integer 1 and compares, so 2 is not equal to it. Never compare with true or false. Write if (ready) and if (!ready) for booleans, and an explicit test like if (items > 0) for numbers.

Some more bool facts:

  • sizeof(bool) is implementation-defined, and 1 on every common platform. A bool uses a whole byte; to pack many flags tightly, see std::bitset or the bitwise operators.
  • Brace initialization refuses narrowing into bool: bool b{2}; is a compile error, while bool b = 2; quietly gives true.
  • Pointers convert to bool too, so if (ptr) means "if ptr is not null" (see Pointers).
  • Name booleans as questions or states: is_valid, has_children, done. Then if (is_valid) reads like English.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. char c = 'C'; std::println("{}", c + 2); What is printed?

    c is promoted to int for the addition, so c + 2 is the int 69 (the code of 'E'), and an int prints as a number. Storing it back into a char would print E.
  2. 2. What value does '9' - '0' have?

    The digit characters have consecutive codes (48 to 57), so subtracting '0' gives the digit's value, 9.
  3. 3. Why should you write std::isalpha(static_cast<unsigned char>(c)) instead of std::isalpha(c)?

    The <cctype> functions accept values representable as unsigned char (or EOF). Plain char is signed on x86, so bytes above 127 become negative.
  4. 4. int n = 3; Which condition is true?

    true converts to 1, so n == true compares 3 with 1 and is false. false converts to 0, and 3 != 0 is true. Better: write n != 0 or if (n).
  5. 5. Which statement about plain char is correct?

    char, signed char and unsigned char are three distinct types. Plain char is signed on x86 and unsigned on ARM Linux, for example.

Summary

  • char is a one-byte integer holding a character code. Arithmetic on it is integer arithmetic ('A' + 1 is the int 66), and ch - '0' turns a digit into its value.
  • Plain char may be signed (x86) or unsigned (ARM Linux); char, signed char and unsigned char are distinct types. Use unsigned char, std::uint8_t or std::byte for raw bytes.
  • Always pass static_cast<unsigned char>(c) to <cctype> functions, and cast std::toupper's int result back to char.
  • wchar_t, char8_t, char16_t and char32_t exist for wide and Unicode encodings; for most code, store UTF-8 in std::string.
  • Zero and null convert to false, everything else to true; true/false convert to 1/0. Never compare with == true.
  • std::println prints bool as true/false; std::cout needs std::boolalpha.

Next: Type Deduction with auto, where you let the compiler work out types for you, and learn exactly what it deduces.