Lesson 32 +10 XP

Characters

Characters

A char stores a single character - a letter, a digit, a symbol. It's small, simple, and sneakily clever under the hood.

char and single quotes

A char literal is written in single quotes (double quotes would make it a string):

char letter = 'A';
char digit = '7';
char symbol = '!';

Each of these stores exactly one character.

A char is secretly a number

Here's the trick: a char actually stores a whole number - the character's code. Most systems use ASCII, where 'A' is code 65, 'B' is 66, 'a' is 97, and '0' is 48.

char c = 'A';
cout << c;      // prints A
cout << (int)c; // prints 65, the ASCII code

Because a char is a number, you can even do arithmetic with it:

char next = 'A' + 1;   // 'B' (65 + 1 = 66)

Sizes

A char is 1 byte - the smallest addressable unit of memory. Whether it can hold negative values is not standardized; most systems make plain char signed.

Char sizes summary

  • char - 1 byte, the base unit.
  • wchar_t - a "wide" character for larger character sets (like non-ASCII text).
  • Newer code often prefers char8_t (UTF-8), char16_t, and char32_t for international text.

TL;DR

  • char stores a single character, written in single quotes.
  • It's really a number: the ASCII code ('A' is 65).
  • Because it's numeric, you can do arithmetic: 'A' + 1 is 'B'.
  • A char is 1 byte - the smallest unit of memory.
  • Wide types (wchar_t, char16_t) handle bigger character sets.