Question 8
Back to Exercise
The programmer expected the counter to be 3. What does the program print, and why?
#include <stdio.h>
int main(void) {
int counter = 0;
size_t total = 0;
for (int i = 0; i < 3; i++)
total += sizeof(counter++);
printf("%d %zu\n", counter, total);
return 0;
}
- A 3 12
- B 0 12 – sizeof only looks at the type of its operand and never executes counter++ Correct
- C 3 3
- D It does not compile
Correct Answer: Option B
Each sizeof(counter++) is just the constant 4 (the size of int), so total is 12 and counter never changes. Keep side effects out of sizeof.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!