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?

  1. AIt prints 3 2 1 0 and ends
  2. BIt prints 3 2 1 and ends
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. A program that sets "char c = 200;" and prints c with %d in printf printed −56 when compiled and run with gcc for x86-64 Linux, and 200 with gcc for Arm Linux. Which of the following is the reason for the difference?
  2. Which of the following is the output when the code above, with b++ on the right side of && and ||, is executed?
  3. Which of the following is the output when the switch statement above, which contains a case without break, is executed?
  4. Which of the following is the output when the program above is executed?
  5. When the function f above is called three times in a row, which of the following is the return value of the third call?