C++ – How to Ensure uintXX_t is the Unsigned Type of intXX_t

c++cstdintlanguage-lawyer

is it a guaranteed by the standard that this is true?

Like if for example I am using windows, int and long have same size will it be guaranteed that if int32_t is for example an alias to a signed int it is guaranteed that uint32_t is an alias to unsigned int and not unsigned long.

I need this to avoid UB while type aliasing.

Best Answer

[cstdint.syn]p2:

The header defines all types and macros the same as the C standard library header <stdint.h>.
See also: ISO/IEC 9899:2018, 7.20

ISO/IEC 9899:2018 §7.20.1p1

When typedef names differing only in the absence or presence of the initial u are defined, they shall denote corresponding signed and unsigned types as described in 6.2.5; an implementation providing one of these corresponding types shall also provide the other.

It does not take too much more reading of the standards to guarantee that for all N, static_assert(std::is_same_v<std::intN_t, std::make_signed_t<std::uintN_t>>); will succeed if std::intN_t is defined.