Skip to main content
Engineering LibreTexts

4.4.3: Literals and Constants - Characters

  • Page ID
    29034
  • Character Literal

    This refers to the literals that are used to store a single character within a single quote. To store multiple characters, one needs to use a character array. Storing more than one character within a single quote will throw a warning and displays just the last character of the literal. It gives rise to the following two representations:

    • char type: This used to store normal character literal or the narrow-character literals. This is supported by both C and C++.

      Example:

      // For C++
      char chr = 'G';
      
    • wchar_t type: This literal is supported only in C++ and not in C. If the character is followed by L, then the literal needs to be stored in wchar_t. This represents wide-character literal.

      Example:

      // For C++
      wchar_t chr = L'G';
      

    Example:

    #include <iostream>
    using namespace std;
      
    int main()
    {   // constant char literal
        const char charVal = 'A';
      
        // wide char literal
        const wchar_t charVal1 = L'A';
      
        cout << "Character Literal: " << charVal << "\n";
        cout << "Wide_Character Literal: " << charVal1 << "\n";
      
        return 0;
    } 

    Output:

    Character Literal: A
    

    Escape Sequences: There are various special characters that one can use to perform various operations.

    Adapted from:
    "Types of Literals in C/C++ with Examples" by Chinmoy Lenka, Geeks for Geeks