C++ char

In C++, the char keyword is used to declare character type variables. A character variable can store only a single character.

Example 1: Printing a char variable

Output

Character = h

In the example above, we have declared a character type variable named ch. We then assigned the character h to it.

Note: In C and C++, a character should be inside single quotation marks. If we use, double quotation marks, it's a string.


ASCII Value

In C and C++, an integer (ASCII value) is stored in char variables rather than the character itself. For example, if we assign 'h' to a char variable, 104 is stored in the variable rather than the character itself. It's because the ASCII value of 'h' is 104.

Here is a table showing the ASCII values of characters A, Z, a, z and 5.

Characters ASCII Values
A 65
Z 90
a 97
z 122
5 53

To learn more about ASCII code, visit the ASCII Chart.


Example 2: Get ASCII Value of a Character

Output

ASCII value = 104

We can get the corresponding ASCII value of a character by using int() when we print it.


We can assign an ASCII value (from 0 to 127) to the char variable rather than the character itself.

Example 3: Print Character Using ASCII Value

Output

Character = h

Note: If we assign '5' (quotation marks) to a char variable, we are storing 53 (its ASCII value). However, if we assign 5 (without quotation marks) to a char variable, we are storing the ASCII value 5.


C++ Escape Sequences

Some characters have special meaning in C++, such as single quote ', double quote ", backslash \ and so on. We cannot use these characters directly in our program. For example,

// This code shows an error
char character = ''';

Here, we are trying to store a single quote character ' in a variable. But this code shows a compilation error.

So how can we use those special characters?

To solve this issue, C++ provides special codes known as escape sequences. Now with the help of escape sequences, we can write those special characters as they are. For example,

// does not show error
char character = ' \' ';

Here, \' is an escape sequence that allows us to store a single quote in the variable.

The table below lists escape sequences of C++.

Escape Sequences Characters
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null Character

Example 4: Using C++ Escape Sequences

Output

A	5
a

In the above program, we have used two escape sequences: the horizontal tab \t and the new line \n.