Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the expression a==--a true in if statement? [duplicate]

    #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?

like image 466
Pankaj Mahato Avatar asked Jan 25 '14 12:01

Pankaj Mahato


1 Answers

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).

like image 67
Sergey Kalinichenko Avatar answered Oct 27 '22 23:10

Sergey Kalinichenko