Search code examples
coperator-precedence

Operator precedence in C for the statement z=++x||++y&&++z


I was studying operator precedence and I am not able to understand how the value of x became 2 and that of y and z is 1

x=y=z=1;

z=++x||++y&&++z;

This evaluates to

x=2 y=1 z=1

Solution

  • ++ has higher priority than ||, so the whole RHS of the assignment boils down to an increment of x and an evaluation to a truth value (1).

    z = ++x         ||  ++y&&++z;
        truthy (1)     never executed
    

    This is because ++x evaluates to true and the second branch is not executed. ++x is 2 which, in a boolean context, evaluates to true or 1. z takes the value of 1, giving you the observed final state.