Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?  

int main()
    {
        int a = 10;
        if (a == a--)
            printf("TRUE 1\t");
        a = 10;
        if (a == --a)
            printf("TRUE 2\t");
    }

 

  • A.TRUE 1
  • B.TRUE 2
  • C.TRUE 1  TRUE 2
  • D.No output

Answer: C

Correct answer: TRUE 1 TRUE 2

Both comparisons read a in one operand while modifying it in the other, with no sequence point between, so both are formally undefined behaviour. The expression modifies a variable more than once, and reads it as well, with no sequence point in between. The C standard makes that undefined behaviour, so the answer listed is what one common compiler happens to produce - another compiler, or another optimisation level, may give something else, and no program should depend on it. What the question is really illustrating is that a == a-- and a == --a cannot be reasoned about at all - not that one is true and the other false.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.