C Programming Basics
uint8_t x = 250;
for (int i = 0; i < 10; i++)
x++;
printf("%d\n", x);uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?
- A4
- B255
- C260
Show answer and explanation
Answer: A. 4
uint8_t can represent 0 to 255. The standard specifies that a value that does not fit in an unsigned integer type becomes its remainder modulo 2⁸ = 256, so counting up by 1 from 250, the value after 255 goes back to 0. After 10 increments, the result is 250 + 10 = 260 modulo 256, which is 4. In contrast, overflow in signed integer arithmetic is undefined behavior.
- A. Correct. It is 260 modulo 256, which is 4.
- B. This is the value obtained by assuming it stops (saturates) at the maximum 255. Unsigned integer types wrap back toward 0.
- C. This is 250 plus 10 without considering overflow. uint8_t cannot hold values of 256 or more.