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_t2000xC8A 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 */xuint8_t2550xFF255: every bit is 1.
255 + 1needs 9 bits2560x100256 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_twrapped00x0What is left is 0000 0000: 0.
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_t2550xFFsint8_t−10xFFuint8_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 1111is 127, the largest.1000 0000is −128, the smallest.1111 1111is −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:
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, 1 | x + 1 |
ret | return 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, 2147483647 | INT_MAX |
cmp w0, w1 | compare x with it |
beq .L5 | equal? go to return -1 |
add w0, w0, 1 | x + 1 |
ret | return it |
The check stays.
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 */As written
ais auint8_tholding 200, andbis auint8_tholding 100.auint8_t2000xC8buint8_t1000x64Both become int
Before any math, C turns every type smaller than
intintoint. This is called integer promotion. The value does not change; it just gets more bits. The new bits are all 0.aintnew bits dashed2000xC8bintnew bits dashed1000x64The math
200 + 100 = 300. That fits in
int, so it is the result.a + bint3000x12CStored in sbits dropped
sis auint8_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 dropped3000x12Csuint8_tlowest bits kept440x2C
Three things follow from this:
- The result is an
int.sizeof(a + b)is 4, not 1. And the result can be bigger than 255 or negative: for twouint8_tvalues, 10 − 20 is −10, not 246. - Values are cut only when stored.
uint8_t s = a + b;keeps the lowest 8 bits of theintresult. - Small types do not overflow.
int8_t y = 127; y = y + 1;works out 127 + 1 as anint, which is 128 with no trouble. Storing 128 back intoydoes 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! */As written
-1is anintholding −1, and1uis anunsigned intholding 1.-1int−10xFFFFFFFF1uunsigned int10x1Converted to unsigned intvalue changes
intmeetsunsigned int, so C converts-1tounsigned intbefore comparing or adding. The bits stay exactly the same, butunsigned inthas no negative numbers: −1 becomes 4,294,967,295.-1unsigned intwas −14,294,967,2950xFFFFFFFFThe 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:
- Compiler warnings. Build with
-Wall -Wextraand GCC reports "comparison of integer expressions of different signedness". In C,-Wallalone does not catch it. - Small unsigned types are safe here. A
uint8_toruint16_tbecomesintfirst, so-1 < (uint8_t)1is true. The trap isunsigned intand wider:uint32_t, andsize_t, the typesizeofgives.
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
| When | What happens | C says |
|---|---|---|
| Unsigned math goes past the top or below 0 | Wraps around. Always, on every chip. | Defined |
| A type smaller than int is used in math | It becomes int first. | Defined |
| A value is stored in an unsigned type too small for it | Only the lowest bits are kept. | Defined |
| A value is stored in a signed type too small for it | GCC keeps the lowest bits. Other compilers may differ. | Up to the compiler |
| int or long math goes past its limits | Nothing is promised. Checks that rely on it may be deleted. | Undefined |
| An int meets an unsigned int | The 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
xuint8_t2530xFD- Outside the ring: values as unsigned (uint8_t).
- Dashed lines: where counting wraps. Red when the value just crossed it.
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.
uint8_t a = 200, b = 100;
uint8_t s = a + b;As written1 of 4
As written
ais auint8_tholding 200, andbis auint8_tholding 100.auint8_t2000xC8buint8_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;As written
ais auint8_tholding 200, andbis auint8_tholding 100.auint8_t2000xC8buint8_t1000x64Both become int
Before any math, C turns every type smaller than
intintoint. This is called integer promotion. The value does not change; it just gets more bits. The new bits are all 0.aintnew bits dashed2000xC8bintnew bits dashed1000x64The math
200 + 100 = 300. That fits in
int, so it is the result.a + bint3000x12CStored in rbits dropped
ris auint8_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 dropped3000x12Cruint8_tlowest bits kept440x2C
3Practice
Predict the value
Work out each answer, then press Check. After checking you see every step C took.
Challenge
Four harder ones. Each is a bug that turns up in real firmware, and each has a hint if you get stuck.
Sources
- C standard (C11, draft N1570): 5.2.4.2.1
INT_MAXand the other limits; 6.2.5p9 unsigned math wraps around; 6.2.5p15 plaincharis 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 anint, 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-compareand-Wtype-limitsare turned on by-Wextra. - Arm's rules for C on 32-bit ARM (AAPCS32) and 64-bit ARM (AAPCS64): plain
charis unsigned;longis 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) andgcc -m32(same type sizes as 32-bit ARM). The example programs were compiled and run,-fsanitize=undefinedconfirmed the overflow cases, and the ARM64 instructions are GCC's own output.