Type char, referred to as character type, is used to represent a single character.
The type can store characters such as 'a', 'Z' etc.
The size of a character type is exactly one byte.
Character literals are enclosed in single quotes '' in C++.
To declare and initialize a variable of type char, we write:
int main() { char c = 'a'; }
Now we can print out the value of our char variable:
#include <iostream> int main() //w ww . j a va2 s. c om { char c = 'a'; std::cout << "The value of variable c is: " << c; }
Once declared and initialized, we can access our variable and change its value:
#include <iostream> int main() /* w w w .java 2s . c om*/ { char c = 'a'; std::cout << "The value of variable c is: " << c; c = 'Z'; std::cout << " The new value of variable c is: " << c; }
The size of the char type in memory is usually one byte.
We obtain the size of the type through a sizeof operator:
#include <iostream> int main() //from w ww. ja va2s . c om { std::cout << "The size of type char is: " << sizeof(char) << " byte(s)"; }
There are other character types
such as wchar_t for holding characters of Unicode character set,
char16_t for holding UTF-16 character sets.
A character literal is a character enclosed in single quotes.
Example: 'a', 'A', 'z', 'X', '0' etc.
Every character is represented by an integer number in the character set.
That is why we can assign both numeric literals and character literals to our char variable:
int main() /*from w ww. j a v a 2 s. co m*/ { char c = 'a'; // is the same as if we had // char c = 97; }
We can write:
char c = 'a';
or we can write
char c = 97;
which is the same, as the 'a' character in ASCII table is represented with the number of 97.