Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

unsigned char — a one-byte unsigned integer type

unsigned char is an unsigned integer type distinct from char and signed char. It occupies one C++ byte, not necessarily eight bits. It is useful for byte values, but undergoes integral promotions in expressions.

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

Syntax

unsigned char name = value;

unsigned char is a standard unsigned integer type distinct from char and signed char. sizeof(unsigned char) is always 1. A C++ byte has at least 8 bits; the type's range is 0 through 2^N - 1, where N is the number of bits in a byte. The range 0–255 applies only to an 8-bit byte.

Before most arithmetic operations, an unsigned char value is promoted to int if int can represent the entire range of unsigned char, or to unsigned int otherwise. Consequently, subtracting two unsigned char values need not produce a result of that type. Converting an integer back to unsigned char produces the congruent value modulo 2^N; static_cast<unsigned char>(-1) produces the type's maximum value. Brace initialization rejects prohibited narrowing rather than performing that conversion.

The type also supports access to object representations: access through an unsigned char glvalue is permitted regardless of the object's type. This does not mean arbitrary byte changes produce a valid object value or that the byte layout is a portable serialization format.

std::cout << value treats an unsigned char as a character; use static_cast<unsigned int>(value) to print a number. The example does not assume an 8-bit byte. If unsigned char promotes to int, zero - 1 is -1, so zero - 1 < zero is true. If it promotes to unsigned int, the subtraction wraps to UINT_MAX, so the comparison is false. The third output line therefore depends on the implementation.

Examples

#include <iostream>

int main() {
    unsigned char value = 42;
    unsigned char zero = 0;
    unsigned char wrapped = static_cast<unsigned char>(-1);

    std::cout << sizeof(value) << '\n';
    std::cout << static_cast<unsigned int>(value) << '\n';
    std::cout << std::boolalpha << (zero - 1 < zero) << '\n';
    std::cout << (wrapped > zero) << '\n';
}

Result

1
42
true
true

The code printed `true` on the third line in the isolated verification environment. On an implementation that promotes `unsigned char` to `unsigned int`, that line is `false`.

Sources