Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

char16_t — UTF-16 code unit type

char16_t is a built-in integral type intended to hold UTF-16 code units. One value does not necessarily represent an entire Unicode character: some code points require a pair of code units.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

char16_t unit = u'A';
const char16_t text[] = u"A\U0001F600";

char16_t is a distinct built-in character and integral type. Its underlying type is std::uint_least16_t, but it is not an alias for that type. It provides at least 16 value bits; do not assume that sizeof(char16_t) == 2. Using the keyword itself requires no header.

The u prefix creates UTF-16 literals: u'A' has type char16_t, while u"A" is a zero-terminated array of const char16_t elements. A character written in a character literal must fit in one UTF-16 code unit; consequently, u'\U0001F600' is ill-formed, whereas u"\U0001F600" is a valid string literal.

A code unit is not the same as a code point or a user-perceived character. In UTF-16, code points outside the Basic Multilingual Plane require a surrogate pair. The char16_t type itself does not validate UTF-16: an array can also contain unpaired surrogates.

The example stores A and U+1F600: three code units plus a terminating zero, making four array elements. Dividing by sizeof(text[0]) counts elements without assuming a byte size. The displayed output is from the environment in which the example ran and is not guaranteed on all implementations. If std::size_t is an alias for unsigned char, count is promoted to int or unsigned int in count - 1, and the subtraction result is printed as a number. If instead std::size_t is an extended unsigned integer type ranked above int, count is not promoted, and overload resolution for << on the result can be ambiguous. The second statement inserts count directly into the stream as std::size_t. If std::size_t is an alias for unsigned char, that insertion writes a character instead of the digit 4. Neither statement prints the UTF-16 text stored in text. This entry targets C++23; the supplied site hosts an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    constexpr char16_t unit = u'A';
    constexpr char16_t text[] = u"A\U0001F600";
    constexpr auto count = sizeof(text) / sizeof(text[0]);

    static_assert(unit == 0x0041);
    static_assert(count == 4);
    static_assert(text[1] == 0xD83D && text[2] == 0xDE00);
    static_assert(text[3] == 0);

    std::cout << "code units: " << count - 1 << '\n';
    std::cout << "array elements: " << count << '\n';
}

Result

code units: 3
array elements: 4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources