Search code examples
clogical-operatorsoperator-precedenceassignment-operator

Precedence in C operators == and ( = )


I have to analyze what some code in C does, and I have a doubt about what happens in a certain line. The code is

#define PRINTX printf("%d\n", x)

void problem() { 
    int x = 2, y, z;
    x *= 3 + 2; PRINTX;
    x *= y = z = 4; PRINTX;
    x = y == z; PRINTX;
    x == (y = z); PRINTX; // This line is the problem
} 

This code snippet prints the resulting numbers:

10
40
1
1  // This result **

the problem is that I'm still trying to figure out why does the last line prints out x = 1, when the operation is x == (y = z). I'm having trouble finding out what that 1 means and the precedence of the operations. Hope someone can help me! :)


Solution

  • Nothing in the last statement changes the value of x, so its value remains unchanged.


    Parens were used to override precedence, forcing the = to be the operand of the ==.

    An operator's operands must necessarily be evaluated before the operator itself, so we know the following:

    • y is evaluated at some point before the =.
    • z is evaluated at some point before the =.
    • x is evaluated at some point before the ==.
    • = is evaluated at some point before ==.

    That's it. All of these are valid orders:

    • z y = x ==
    • y z = x ==
    • x y z = ==
    • etc.

    But whenever x, y and z are evaluated, we can count on the following happening:

    1. = assigns the value of z (currently 4) to y and returns it.
    2. == compares the value of x (currently 1) with the value returned by = (4). Since they're different, == returns 0 (which isn't used by anything).

    As you see, nothing changed x, so it still has the value it previously had (1).