Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

char8_t — UTF-8 code unit type

char8_t is a distinct integral type intended for UTF-8 code units, not an alias of unsigned char. The u8 literal prefix produces data of this type, but one code unit does not necessarily represent a complete Unicode character.

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

Syntax

char8_t unit = u8'A';
const char8_t text[] = u8"\u00E9";

char8_t is a built-in integral type distinct from char and unsigned char; its underlying type is unsigned char. It requires no header. It represents UTF-8 code units rather than arbitrary complete Unicode characters. The type itself does not validate a stored UTF-8 sequence.

The literal u8'A' has type char8_t. A character written in such a literal must fit in one UTF-8 code unit. The string literal u8"\u00E9" has array type with const char8_t elements and contains two code units for U+00E9 followed by a terminating zero. A code unit count is therefore not the same as a character count.

std::u8string, available through <string>, is an alias for std::basic_string<char8_t>. A const char8_t* does not implicitly convert to const char*: an API accepting the latter requires deliberate data adaptation. A separate initialization rule permits char text[] = u8"abc";; this does not make the pointer types compatible.

In the environment where the example was verified, it prints the code unit count excluding the terminator and the numeric values of the units. The output does not depend on the terminal's ability to render UTF-8. The code unit values are cast to unsigned int, but the count expression is not. If std::size_t is an extended unsigned integer type with a rank higher than int, the count expression retains type std::size_t, and overload resolution for << when writing the count to std::cout can be ambiguous. This entry targets C++23; the referenced working draft is an evolving document, not a frozen C++23 publication. The repository compiler setting does not attest production runtime operation.

Examples

#include <iostream>
#include <type_traits>

int main() {
    constexpr char8_t text[] = u8"\u00E9";
    static_assert(!std::is_same_v<char8_t, unsigned char>);
    static_assert(sizeof(text) / sizeof(text[0]) == 3);
    static_assert(text[0] == 0xC3 && text[1] == 0xA9);
    static_assert(text[2] == 0);

    std::cout << sizeof(text) / sizeof(text[0]) - 1 << '\n';
    std::cout << static_cast<unsigned int>(text[0]) << ' '
              << static_cast<unsigned int>(text[1]) << '\n';
}

Result

2
195 169

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