C basics · 2 of 8

Signed, unsigned, overflow, promotion

Wraparound, undefined signed overflow, and how small integer types are promoted to int.

1Read

Bits make a number

A byte is 8 bits, and each bit is a 0 or a 1. Like the digits of a decimal number, each place is worth more than the one to its right: in decimal ten times more, in binary two times more.

uint8_t n = 200;
nuint8_t2000xC8
Each box is one bit. The number under a box is what a 1 in that box is worth: 1 on the right, then each place doubles, up to 128 on the left. With all 8 bits set the total is 255, the largest number a byte can hold.

A uint8_t uses one byte, so it holds 0 to 255. The u means unsigned: no negative numbers.

Unsigned numbers wrap around

What happens when a uint8_t holding 255 gets 1 more? The answer, 256, needs a 9th bit, and there is nowhere to put it. The extra bit is dropped and the value wraps around to 0, like a car's trip counter rolling over.

uint8_t x = 255;
x = x + 1;        /* x is now 0 */
0326496128160192224255 → 0
xuint8_t2550xFF

255: every bit is 1.

255 + 1needs 9 bits2560x100

256 is 1 0000 0000 in binary: the 1 is in bit 8 (marked). x only has bits 0 to 7, so everything from bit 8 up (struck through) is dropped.

xuint8_twrapped00x0

What is left is 0000 0000: 0.

Like the numbers on a clock, the values of a byte go round in a circle. Counting up from 255 lands on 0; counting down from 0 lands on 255. The dashed line at the top marks where it wraps.

C promises this for every unsigned type, on every chip. It works the same going down: 0 − 1 gives 255. A uint32_t wraps too, just further out: 4,294,967,295 + 1 is 0.

Negative numbers: the top bit counts as negative

Signed types such as int8_t, int16_t and int hold negative numbers too. Every chip you will meet stores them the same way, called two's complement: the top bit counts as negative. For 8 bits it is worth −128 instead of +128.

uuint8_t2550xFF
sint8_t−10xFF
Both variables hold the same 8 bits, 1111 1111. As a uint8_t the top bit is worth 128 and the total is 255. As an int8_t the top bit is worth −128, so the total is −128 + 127 = −1.

So an int8_t holds −128 to 127. Three patterns are worth knowing by heart:

  • 0111 1111 is 127, the largest.
  • 1000 0000 is −128, the smallest.
  • 1111 1111 is −1. In any size, −1 is all ones: 0xFF in 8 bits, 0xFFFFFFFF in 32.

To make a number negative, flip every bit and add 1. 5 is 0000 0101; flipped it is 1111 1010; add 1 and you get 1111 1011, which is −5.

Put the two readings side by side and you get one ring with two sets of names:

00323264649696128−128160−96192−64224−32255 → 0127 → −128
Every position on the ring is one bit pattern with two names. Outside: the uint8_t value. Inside: the int8_t value. The right half is the same both ways (0 to 127). On the shaded left half, the patterns with the top bit set, int8_t counts −128 up to −1. So unsigned numbers wrap at the top (255 → 0) and signed ones at the bottom (127 → −128).

Signed overflow is not allowed

An int is 32 bits on ARM and holds −2,147,483,648 to 2,147,483,647. These limits are called INT_MIN and INT_MAX (from <limits.h>). What is INT_MAX + 1?

For unsigned types the answer was "it wraps". For signed types C gives no answer at all. Going past the limits of a signed type during math is called signed overflow, and it is undefined behaviour: the C standard sets no rules for what happens. It is a bug, even when the program seems to work.

Undefined does not just mean "some odd value". The compiler may assume it never happens, and it uses that to simplify your code. Here is what that does to a check for overflow:

The check written with overflow

int add_one(int x)
{
    if (x + 1 < x)      /* overflowed? */
        return -1;
    return x + 1;
}

ARM64 instructions from GCC

add w0, w0, 1x + 1
retreturn it

The check is gone.

The check written without overflow

int add_one(int x)
{
    if (x == INT_MAX)   /* would overflow? */
        return -1;
    return x + 1;
}

ARM64 instructions from GCC

mov w1, 2147483647INT_MAX
cmp w0, w1compare x with it
beq .L5equal? go to return -1
add w0, w0, 1x + 1
retreturn it

The check stays.

Under each function are the ARM64 instructions GCC made from it, with what each one does. On the left, GCC reasons: signed overflow never happens in a correct program, so x + 1 < x is always false, and it deletes the check. It does this even with optimization turned off. On the right, nothing overflows, so the check is kept.

To check safely, compare against the limit before doing the math, as on the right. Or do the math in an unsigned type, where wrapping is allowed.

Only math done at int size or bigger can overflow. Smaller types such as int8_t cannot, for the reason in the next section.

Small types grow before math

C never does math on types smaller than int. Before any +, −, * or comparison, a uint8_t, int8_t, uint16_t, int16_t or char is converted to int. This is called integer promotion. ARM works the same way: its add instruction always works on a whole 32- or 64-bit register, never on a single byte.

uint8_t a = 200, b = 100;
uint8_t s = a + b;      /* s is 44 */
  1. As written

    a is a uint8_t holding 200, and b is a uint8_t holding 100.

    auint8_t2000xC8
    buint8_t1000x64
  2. Both become int

    Before any math, C turns every type smaller than int into int. This is called integer promotion. The value does not change; it just gets more bits. The new bits are all 0.

    aintnew bits dashed2000xC8
    bintnew bits dashed1000x64
  3. The math

    200 + 100 = 300. That fits in int, so it is the result.

    a + bint3000x12C
  4. Stored in sbits dropped

    s is a uint8_t: 8 bits, 0 to 255. Only the lowest 8 bits are kept, 0010 1100, which is 44. The other 24 bits are dropped. C defines this for unsigned types.

    a + bintstruck bits are dropped3000x12C
    suint8_tlowest bits kept440x2C

Three things follow from this:

  1. The result is an int. sizeof(a + b) is 4, not 1. And the result can be bigger than 255 or negative: for two uint8_t values, 10 − 20 is −10, not 246.
  2. Values are cut only when stored. uint8_t s = a + b; keeps the lowest 8 bits of the int result.
  3. Small types do not overflow. int8_t y = 127; y = y + 1; works out 127 + 1 as an int, which is 128 with no trouble. Storing 128 back into y does not fit; C leaves that to each compiler, and GCC wraps it to −128. That is not undefined behaviour.

A negative number keeps its value when it grows: the new bits are copies of its top bit. −100 as an int8_t is 0x9C; as an int it is 0xFFFFFF9C.

Mixing signed and unsigned

When an int meets an unsigned int in math or a comparison, C converts the int to unsigned int. The bits stay the same, but a negative number now reads as a huge one.

if (-1 < 1u)            /* false! */
  1. As written

    -1 is an int holding −1, and 1u is an unsigned int holding 1.

    -1int−10xFFFFFFFF
    1uunsigned int10x1
  2. Converted to unsigned intvalue changes

    int meets unsigned int, so C converts -1 to unsigned int before comparing or adding. The bits stay exactly the same, but unsigned int has no negative numbers: −1 becomes 4,294,967,295.

    -1unsigned intwas −14,294,967,2950xFFFFFFFF
  3. The comparison

    4,294,967,295 < 1 is false. A comparison gives an int: 1 for true, 0 for false.

    -1 < 1u = 0 (false)

The u on 1u makes it unsigned. Real code hits this with a variable instead, for example int i = -1; unsigned int len = 5; if (i < len) is false.

Two things help:

  1. Compiler warnings. Build with -Wall -Wextra and GCC reports "comparison of integer expressions of different signedness". In C, -Wall alone does not catch it.
  2. Small unsigned types are safe here. A uint8_t or uint16_t becomes int first, so -1 < (uint8_t)1 is true. The trap is unsigned int and wider: uint32_t, and size_t, the type sizeof gives.

On ARM, plain char has no sign

A char written alone, without signed or unsigned in front, is a special case: C lets each platform choose. On ARM it is unsigned (0 to 255). On x86 PCs it is signed (−128 to 127). So char c = 200; holds 200 on ARM and −56 on a PC.

Use uint8_t for raw bytes and int8_t for small signed numbers. Keep plain char for text.

The rules on one page

WhenWhat happensC says
Unsigned math goes past the top or below 0Wraps around. Always, on every chip.Defined
A type smaller than int is used in mathIt becomes int first.Defined
A value is stored in an unsigned type too small for itOnly the lowest bits are kept.Defined
A value is stored in a signed type too small for itGCC keeps the lowest bits. Other compilers may differ.Up to the compiler
int or long math goes past its limitsNothing is promised. Checks that rely on it may be deleted.Undefined
An int meets an unsigned intThe int is converted to unsigned. −1 becomes 4,294,967,295.Defined

2Watch

Counting past the end

A uint8_t counts up past 255 and back down past 0. Then an int8_t goes past 127. Use the arrows to step through, or press play.

uint8_t x = 253;

Start at 2531 of 10

0326496128160192224255 → 0
xuint8_t2530xFD
  • Outside the ring: values as unsigned (uint8_t).
  • Dashed lines: where counting wraps. Red when the value just crossed it.
x is a uint8_t holding 253. The pointer shows where 253 sits on the ring of all 256 byte values.

Inside an expression

Pick an example and step through what C does to it, one stage at a time. Stages where something surprising happens are marked in red.

Pick an example
uint8_t a = 200, b = 100;
uint8_t s = a + b;

As written1 of 4

  1. As written

    a is a uint8_t holding 200, and b is a uint8_t holding 100.

    auint8_t2000xC8
    buint8_t1000x64

Try your own

Choose the types, the values and the operator. Values can be negative, or hex with 0x in front.

uint8_t a = 200;
uint8_t b = 100;
uint8_t r = a + b;
  1. As written

    a is a uint8_t holding 200, and b is a uint8_t holding 100.

    auint8_t2000xC8
    buint8_t1000x64
  2. Both become int

    Before any math, C turns every type smaller than int into int. This is called integer promotion. The value does not change; it just gets more bits. The new bits are all 0.

    aintnew bits dashed2000xC8
    bintnew bits dashed1000x64
  3. The math

    200 + 100 = 300. That fits in int, so it is the result.

    a + bint3000x12C
  4. Stored in rbits dropped

    r is a uint8_t: 8 bits, 0 to 255. Only the lowest 8 bits are kept, 0010 1100, which is 44. The other 24 bits are dropped. C defines this for unsigned types.

    a + bintstruck bits are dropped3000x12C
    ruint8_tlowest bits kept440x2C

3Practice

Predict the value

Work out each answer, then press Check. After checking you see every step C took.

  1. Q1 What does x hold at the end?

    uint8_t x = 255;
    x = x + 1;
  2. Q2 What does s hold?

    uint8_t a = 200, b = 100;
    uint8_t s = a + b;
  3. Q3 Same a and b. How many bytes is a + b?

    uint8_t a = 200, b = 100;
    printf("%zu\n", sizeof(a + b));
  4. Q4 What does d hold?

    uint32_t a = 10, b = 20;
    uint32_t d = a - b;
  5. Q5 Now the same subtraction with uint8_t. What does d hold?

    uint8_t a = 10, b = 20;
    int d = a - b;
  6. Q6 What does this print?

    if (-1 < 1u)
        puts("yes");
    else
        puts("no");
    It prints
  7. Q7 On ARM with GCC:

    int8_t y = 127;
    y = y + 1;
    Is y + 1 undefined behaviour?
  8. Q8 Plain char, no signed or unsigned in front:

    char c = 200;
    if (c < 0) …
    On ARM, is c < 0?
    On a PC (x86), is c < 0?

Challenge

Four harder ones. Each is a bug that turns up in real firmware, and each has a hint if you get stuck.

  1. C1 The hidden overflow. Two unsigned 16-bit sizes are multiplied into a 32-bit result. Nothing here is signed, or is it?

    uint16_t w = 65535, h = 65535;
    uint32_t area = w * h;
    Is w * h defined behaviour?
    Which line gives 4,294,836,225?
    Show a hint

    What type are w and h by the time they are multiplied? What is the largest value that type can hold?

  2. C2 Ticks across the wrap. A timer counts up in a uint32_t and wraps to 0 after 4,294,967,295. Firmware measures how long something took.

    uint32_t start = 4294967290u;   /* tick count when we started */
    uint32_t now   = 5;             /* the counter has wrapped since */
    uint32_t elapsed = now - start;
    Show a hint

    Count it by hand first: how many ticks from 4,294,967,290 up to the wrap, and then on to 5?

  3. C3 long on two chips. The L makes −1 a long, and the u makes 1 an unsigned int.

    if (-1L < 1u)
        puts("less");
    else
        puts("not less");
    What does ARM32 print?
    What does ARM64 print?
    Show a hint

    How big is a long on each chip? Can that long hold every value an unsigned int can?

  4. C4 The countdown. A loop meant to blink an LED for 3, 2, 1, 0.

    for (uint8_t i = 3; i >= 0; i--)
        blink_led();
    How many times does blink_led() run?
    Show a hint

    What comes after 0 when a uint8_t counts down? Can a uint8_t ever be below 0?

Sources

  • C standard (C11, draft N1570): 5.2.4.2.1 INT_MAX and the other limits; 6.2.5p9 unsigned math wraps around; 6.2.5p15 plain char is signed or unsigned, chosen by the platform; 6.2.6.2p2 how negative numbers are stored; 6.3.1.1p1 to p2 integer promotion; 6.3.1.3 converting to a smaller type (p2 unsigned keeps the low bits, p3 signed is up to the compiler); 6.3.1.8 what happens when two different types meet; 6.5p5 signed overflow is undefined; 6.5.8p6 a comparison gives an int, 1 or 0.
  • C23 (draft N3096), 6.2.6.2: signed integers must use two's complement.
  • GCC manual, Integers implementation: GCC supports only two's complement, and storing a value that does not fit in a signed type keeps the low bits. Warning options: -Wsign-compare and -Wtype-limits are turned on by -Wextra.
  • Arm's rules for C on 32-bit ARM (AAPCS32) and 64-bit ARM (AAPCS64): plain char is unsigned; long is 32 bits on ARM32 and 64 bits on ARM64.
  • Checked with GCC 13.3: every value in the visuals comes from a model of these rules that is tested against more than 5,700 results from each of aarch64-linux-gnu-gcc (64-bit ARM) and gcc -m32 (same type sizes as 32-bit ARM). The example programs were compiled and run, -fsanitize=undefined confirmed the overflow cases, and the ARM64 instructions are GCC's own output.