Question

    #include <stdio.h>

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

        if (a == --a)
            printf("TRUE 2\t");
    }

Why is the second if statement true?

Output is: TRUE 1 TRUE 2

Is this happening due to Undefined behavior because I am comparing same variable with its decremented value?

Was it helpful?

Solution

Correct, the condition evaluates to true because you see undefined behavior: if a variable with an operator that has side effects is used in an expression, it is illegal to use the same variable again in an expression that has no sequence points (== does not have sequence points).

This is because the compiler is free to apply the side effect of -- at any time that it wishes, as long as the value that is used when evaluating the expression is correct (i.e. the value before the decrement for postfix notation, or the value after the decrement for the prefix notation).

OTHER TIPS

a-- decrements a after the expression has evaluated, effectively meaning when a == a is calculated, it's 10 == 10, which is true.

--a decrements a before the expression has evaluated, effectively meaning when a == a is actually calculated, a has already been decremented, so it's 9 == 9, which is again true.

Pre and post decrements can't happen in the middle of expressions. They happen before or after them.

This is because associativity of == operator is left to right.

a==a--

In this expression, first both sides will be compared (10==10), and then a is decreased to 9

a==--a 

in this expression first the value of a is decreased to 9 then compared to a (which has become 9)

So, both are true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top