4.4.3: Literals and Constants - Characters
- Page ID
- 29034
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
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