C++ char Data Type
In this page:
The char Type
The char type stores a single character, occupying exactly one byte of memory, and is used for individual letters, digits, symbols, or small integer values across C++ programs.
Example: The char Type
#include <iostream>
int main() {
char initial = 'D';
std::cout << initial << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Character Literals
A character literal is written between single quotes, such as A or 7, and can also represent special characters using escape sequences like '\t' for tab or '\n' for newline.
Example: Character Literals
#include <iostream>
int main() {
char letter = 'A';
char tab = '\t';
char newline = '\n';
std::cout << letter << tab << "end" << newline;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Characters as Small Integers
Internally, a char is stored as a small integer representing its ASCII code, which means arithmetic operations work directly on characters, letting code shift from one letter to another by adding or subtracting numbers.
Example: Characters as Small Integers
#include <iostream>
int main() {
char letter = 'A';
char next = letter + 1; // shifts to 'B' via ASCII arithmetic
std::cout << next << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
signed char vs unsigned char
Whether char is signed or unsigned by default depends on the compiler, so signed char and unsigned char explicitly choose between a range that includes negative numbers or one that extends further into positive numbers.
Example: signed char vs unsigned char
#include <iostream>
int main() {
signed char s = -100;
unsigned char u = 200;
std::cout << (int)s << " " << (int)u << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
char with cin and cout
Reading and writing a single char with cin and cout works directly, without any special format specifier, since C++'s stream operators automatically know how to handle each type.
Example: char with cin and cout
#include <iostream>
int main() {
char grade = 'B';
std::cout << "Grade: " << grade << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: