Table of Contents
C++ provides wide character types for representing characters that require more storage than the traditional char type. These types are primarily intended to support larger character sets and platform-specific character encodings.
The language defines wchar_t as a built-in type for wide characters. In addition, C++11 introduced char16_t and char32_t to represent UTF-16 and UTF-32 code units, respectively. These types provide more consistent support for Unicode text across different platforms.
Source Code #
#include <iostream>
int main()
{
std::wcout << L"Wide Character: " << L'A' << '\n';
std::cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes\n";
std::cout << "Size of char16_t: " << sizeof(char16_t) << " bytes\n";
std::cout << "Size of char32_t: " << sizeof(char32_t) << " bytes\n";
return 0;
}
Output #
Wide Character: A
Size of wchar_t : 2 bytes
Size of char16_t: 2 bytes
Size of char32_t: 4 bytes
Note: The size of
wchar_tis implementation-dependent. On many Windows systems it is 2 bytes, while on many Linux systems it is 4 bytes.
Explanation #
wchar_tis a built-in type used to store wide characters.char16_tstores UTF-16 code units and always occupies 2 bytes.char32_tstores UTF-32 code units and always occupies 4 bytes.std::wcoutis the standard output stream used for wide characters and wide strings.- The prefix
Lbefore a character or string literal creates a wide-character literal. - The
sizeofoperator returns the storage size of each character type in bytes. - The size of
wchar_tdepends on the compiler and operating system, whereaschar16_tandchar32_thave fixed sizes defined by the C++ standard. return 0;terminates the program successfully.