LearnFrenzy
Sign in Take a free test

Operators and Expressions · Find the Error · Question 8

Bug: expecting sizeof(counter++) to increment Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The programmer expected the counter to be 3. What does the program print, and why?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links