Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

unsigned char — an unsigned byte

unsigned char is an unsigned integer type occupying one C byte; a byte need not contain eight bits.

Version: C23; repository compiler flag, production runtime not attested

Syntax

unsigned char name;
unsigned char buffer[count];

unsigned char stores values from 0 to UCHAR_MAX, which is at least 255. sizeof(unsigned char) is 1; CHAR_BIT from <limits.h> specifies the number of bits per byte. The type has no padding bits.

char, signed char, and unsigned char are distinct types. An unsigned char * can be used to read the bytes of an object's representation, but their ordering is not a portable data format.

For the addition in value++, the unsigned char value is promoted to int if int can represent every value of the type, and to unsigned int otherwise. If the addition has a defined result, converting it back to unsigned char reduces it modulo the mathematical value UCHAR_MAX + 1. But if UCHAR_MAX == INT_MAX, the value is promoted to int, and adding 1 to the initial value UCHAR_MAX overflows int before conversion back to unsigned char. This is undefined behavior, so the example is not guaranteed to store 0 on every conforming C implementation.

Examples

#include <limits.h>
#include <stdio.h>

int main(void)
{
    unsigned char value = UCHAR_MAX;
    value++;
    printf("size=%zu value=%u\n", sizeof value, (unsigned int)value);
    return 0;
}

Result

size=1 value=0

This exact code was run unchanged in an isolated environment, where it printed `size=1 value=0`. That run does not establish a portable guarantee.

Sources