Variable Type char
-
The char data type can hold a single symbol such as a (upper or lower case) letter,
digit, and punctuation mark.
-
All the symbols that can be typed on the keyboard can be represented by char.
-
A complete set of printable characters can be found in Appendix 3.
-
There are also characters which are not printable, and are represented by using the escape symbol '\'
(the backslash character) followed by a letter.
-
In a program, a char literal must be enclosed in a pair of single quotes.
-
However, single quotes are absent in I/O.
-
They can be declared and initiated as follows:
char first_initial = 'M', // for Mark Twain
your_initial; // your initial
cout << "Mark Twain's first initial is: " << first_initial << endl;
cout << "Enter your first initial: ";
cin >> your_initial;
cout << "Your first initial is: " << your_initial << endl;
-
Internal representation of characters:
- Each character has its own unique numeric code, called the ASCII code,
representing the value of the character.
- It is the binary form of this code that is stored in a character's memory location.
- Typically one byte is used to store each character.
- A total of 128 different characters, with ASCII values between 0 and 127,
can be represented using only the rightmost 7 bits.
- For example, from Appendix 3, we see that the ASCII code for 'A' is 65, and that of 'a' is 95.
-
Because of this internal representation in term of (integer) ASCII code, characters can be compared and
ordered so that relational operators <, <=, >, and >= can be applied to characters.
For example, because 65 is less than 95, the statement 'A' < 'a' is true.
The statement char(int('A')+1) == 'B' is also true, since the ASCII value for 'B' is high than that
of 'A' by 1.