LearnFrenzy
Sign in Take a free test

Operators and Expressions · Find the Error · Question 1

Undefined behaviour: x = x++ in a loop Answer, explanation & discussion

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

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    int count = 0;
    for (int i = 0; i < 3; i++)
        count = count++;
    printf("%d\n", count);
    return 0;
}
  • A The loop runs the wrong number of times
  • B count = count++ modifies count twice without a sequence point – undefined behaviour; write count++; Correct
  • C count must be unsigned
  • D There is no bug; it prints 3
Correct Answer: Option B

The postfix increment and the assignment both write count, unordered. Many compilers print 0, some 3. Clang warns "multiple unsequenced modifications to count". Just write count++;.

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