Variable Type char

  1. The char data type can hold a single symbol such as a (upper or lower case) letter, digit, and punctuation mark.

  2. All the symbols that can be typed on the keyboard can be represented by char.

  3. A complete set of printable characters can be found in Appendix 3.

  4. In addition, there are also characters which are not printable and are represented by using the escape symbol '\' (the backslash character) followed by a letter.

  5. In a program, a char literal must be enclosed in a pair of single quotes.

  6. However, single quotes are absent in I/O.

  7. They can be declared and initialized 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;

  8. 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.

    • For example, from Appendix 3, we see that the ASCII code for 'A' is 65, and that of 'a' is 95.

    • 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.


  9. 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.

    E.g., because the ASCII code for 'A' is 65 and that of 'a' is 95, and 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 higher than that of 'A' by 1 (Letter 'B' comes after letter 'A'.).