Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Unsigned integer literal suffix `u`

The suffix `u` or `U` selects an unsigned integer type, not a fixed width. `0u` and `1u` are `unsigned int`; a larger value can require a wider type.

Version: ISO C++23; implementation support may vary

Syntax

integer-literal ::= (binary-literal | octal-literal | decimal-literal | hexadecimal-literal) integer-suffix?
unsigned-suffix ::= u | U
Examples: 0u, 1U, 0b101u, 077u, 0xFFU, 42ul, 42lu, 42ull, 42llu, 42uz, 42zu

In C++23, the unsigned integer literal suffix (u) is written as u or U directly after the digits. It leaves the value unchanged and works with decimal, binary, octal, and hexadecimal literals. When used alone, it selects the first type that can represent the value: unsigned int, unsigned long, then unsigned long long. If none fits, an implementation may use a suitable extended unsigned integer type. If no allowed type fits, the program is ill-formed; the literal is not truncated.

0u and 1u are always unsigned int; unsuffixed 0 and 1 are int. ul starts the search at unsigned long, ull selects unsigned long long among the standard types, and C++23 uz gives std::size_t if the value fits. You can also put u after the other suffix component, as in lu, llu, or zu.

The 32-bit FNV constants 2166136261u and 16777619u both have type unsigned int when that type is 32 bits wide. On other implementations, selection depends on the types' ranges. The suffix does not mean std::uint32_t: that is an optional alias in <cstdint> for an unsigned integer type with exactly 32 bits and no padding bits. If you need an object of that exact type and the alias is available, write, for example, std::uint32_t offset{2166136261u};. The object's type does not change the initializer literal's type.

The literal's type affects auto deduction, overload resolution, and conversions in expressions. For example, -1 < 1u is false: -1 is converted to unsigned int and becomes that type's maximum value. Do not add u merely to silence a signed/unsigned warning.

Examples

#include <iostream>
#include <type_traits>

constexpr const char* kind(int) { return "int"; }
constexpr const char* kind(unsigned int) { return "unsigned int"; }

int main() {
    auto zero = 0u;
    static_assert(std::is_same_v<decltype(zero), unsigned int>);
    static_assert(std::is_same_v<decltype(1u), unsigned int>);

    std::cout << kind(1) << '\n'
              << kind(1u) << '\n';
}

Result

int
unsigned int

The assertions check the type deduced by `auto` from `0u` and the type of `1u`. The calls `kind(1)` and `kind(1u)` select different overloads because each has an exact type match.

Related lessons

  • C++ · Lesson 7 · Advanced · Version: 3

Sources