Table of Contents
C++ provides multiple character data types for storing characters of different sizes and encoding schemes. The char type is commonly used for ordinary characters, while other character types support larger character sets such as Unicode.
This example demonstrates the declaration and use of commonly used character data types.
Source Code #
#include <iostream>
int main()
{
char letter = 'A';
wchar_t wide_letter = L'A';
char16_t utf16_letter = u'A';
char32_t utf32_letter = U'A';
std::cout << "char: " << letter << '\n';
std::cout << "wchar_t size: " << sizeof(wchar_t) << " byte(s)\n";
std::cout << "char16_t size: " << sizeof(char16_t) << " byte(s)\n";
std::cout << "char32_t size: " << sizeof(char32_t) << " byte(s)\n";
return 0;
}
Output #
char: A
wchar_t size: 4 byte(s)
char16_t size: 2 byte(s)
char32_t size: 4 byte(s)
The size of
wchar_tis implementation-defined and may be 2 bytes or 4 bytes depending on the compiler and operating system.
Explanation #
charstores a single ordinary character and is typically used for ASCII text.wchar_tis a wide character type intended to represent a larger character set thanchar.char16_tstores a UTF-16 code unit and is primarily used for UTF-16 encoded text.char32_tstores a UTF-32 code unit and can represent any Unicode code point directly.- The prefixes
L,u, andUcreate wide, UTF-16, and UTF-32 character literals respectively. sizeofis used to determine the storage size of each character type.- The exact size of
wchar_tdepends on the implementation, whilechar16_tandchar32_thave fixed sizes defined by the C++ standard. return 0;terminates the program successfully.