CKTIS / C++
unsigned — unsigned integer types
The unsigned keyword specifies an unsigned integer type; unsigned alone means unsigned int. Learn its valid combinations, modulo arithmetic, and the conversion and comparison pitfalls that arise when mixing signed and unsigned types.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
unsigned name;
unsigned int name;
unsigned char name;
unsigned short [int] name;
unsigned long [int] name;
unsigned long long [int] name;unsigned is a keyword used as a type specifier. On its own, unsigned means exactly unsigned int. Other valid combinations are unsigned char, unsigned short int, unsigned long int, and unsigned long long int; the last three allow omitting int. There are no unsigned float or unsigned bool types. In the displayed syntax, brackets [] indicate an optional element, not literal code.
An unsigned type of width N has a range from 0 to 2^N − 1. Arithmetic performed in that type works modulo 2^N: incrementing the maximum value produces 0. Do not assume that unsigned int has 32 bits; its width is implementation-defined and at least 16 bits. Signed arithmetic overflow follows different rules and results in undefined behavior.
Converting -1 to unsigned produces that type's maximum value, not an error. Mixing signed and unsigned types invokes promotions and the usual arithmetic conversions. In -1 < 1u, -1 is converted to unsigned int, so the result is false. By contrast, operands of type unsigned char or unsigned short can be promoted to int; not every expression involving them is evaluated as unsigned.
The example demonstrates both effects without assuming a particular type width. This entry targets C++23; the supplied source is an evolving standard draft, not a frozen C++23 publication. The compiler flag does not attest a production environment.
Examples
#include <iostream>
int main() {
unsigned counter = static_cast<unsigned>(-1);
++counter;
std::cout << "counter=" << counter << '\n';
std::cout << std::boolalpha
<< "comparison=" << (-1 < 1u) << '\n';
}
Result
counter=0 comparison=false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.