Table of Contents
C++ supports Unicode character literals for representing characters beyond the ASCII character set. Unicode enables programs to store and process text from many languages using a standardized character encoding.
This example demonstrates how to declare Unicode character literals using char16_t and char32_t.
Source Code #
#include <iostream>
int main()
{
char16_t symbol16 = u'Ω';
char32_t symbol32 = U'😀';
std::cout << "char16_t size: " << sizeof(symbol16) << " byte(s)\n";
std::cout << "char32_t size: " << sizeof(symbol32) << " byte(s)\n";
return 0;
}
Output #
char16_t size: 2 byte(s)
char32_t size: 4 byte(s)
Unicode characters are stored in the variables, but they are not printed in this example because
std::coutdoes not directly support outputtingchar16_tandchar32_tcharacter values.
Explanation #
char16_t symbol16 = u'Ω';declares a UTF-16 character and initializes it with the Unicode characterΩ.char32_t symbol32 = U'😀';declares a UTF-32 character and initializes it with the Unicode character 😀.- The prefix
ucreates a UTF-16 character literal of typechar16_t. - The prefix
Ucreates a UTF-32 character literal of typechar32_t. sizeof(symbol16)returns the storage size of a UTF-16 code unit, which is 2 bytes.sizeof(symbol32)returns the storage size of a UTF-32 code unit, which is 4 bytes.- Unicode support allows C++ programs to represent characters from many writing systems instead of being limited to the basic ASCII character set.
return 0;terminates the program successfully.