Search code examples
c++c++11charactersizeofwidechar

Guarantee on size ordering on char, wchar_t, char16_t, char32_t


Does the C++ standard provide any guarantee on the ordering of the size in bytes of char, wchar_t, char16_t, char32_t? (any extract from the standard is welcome)

For example do I have the guarantee that:

sizeof(char) <= sizeof(wchar_t) <= sizeof(char16_t) <= sizeof(char32_t)

Solution

  • It's 1 == sizeof(char) <= sizeof(wchar_t) and 1 == sizeof(char) <= sizeof(char16_t) <= sizeof(char32_t).

    5.3.3/1 Sizeof [expr.sizeof]

    ... sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1. ... [ Note: in particular, sizeof(bool), sizeof(char16_t), sizeof(char32_t), and sizeof(wchar_t) are implementation-defined.75 — end note ].

    3.9.1/5 Fundamental types [basic.fundamental]

    ... Type wchar_t shall have the same size, signedness, and alignment requirements (3.11) as one of the other integral types, called its underlying type. Types char16_t and char32_t denote distinct types with the same size, signedness, and alignment as uint_least16_t and uint_least32_t, respectively, in <cstdint>, called the underlying types.

    Update: I haven't found it in the standard. cppreference says for uint_leastN_t:

    smallest unsigned integer type with width of at least 8, 16, 32 and 64 bits respectively

    Note that sizeof(char)==1 does not mean that a char has 8 bits. See also C++ FAQ. cppreference says about CHAR_BIT:

    number of bits in byte

    1.7/1 The C ++ memory model [intro.memory]

    The fundamental storage unit in the C ++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set (2.3) ...