C Programming Basics
unsigned int i;
for (i = 3; i >= 0; i--)
printf("%u ", i);unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?
- AIt prints 3 2 1 0 and ends
- BIt prints 3 2 1 and ends
- CAfter printing 3 2 1 0 it does not end, and keeps printing decreasing values starting from 4294967295
Show answer and explanation
Answer: C. After printing 3 2 1 0 it does not end, and keeps printing decreasing values starting from 4294967295
i is unsigned, so it can never become negative, and the condition i >= 0 is always true. Executing i-- when i is 0 wraps it to 2³² − 1 = 4294967295, and the loop does not end but goes on printing 4294967294, 4294967293 and so on. To count down to 0, use int or change the loop, as in for (i = 4; i-- > 0; ). With gcc, -Wextra gives a warning that this comparison is always true.
- A. i >= 0 is also true when i is 0, so the loop does not end at 0.
- B. The condition is also true when i is 0, so 0 is printed as well, and the loop keeps going after that.
- C. Correct. Subtracting 1 from the unsigned i at 0 gives 4294967295, and the condition is always true.