Jayant Jayant -4 years ago 139
C Question

How to solve this logical expression?

Please tell how to solve it by associativity and precedence:


int main()
int i=-3,j=2,k=0,m;
printf("%d %d %d %d",i,j,k,m);
return 0;

Answer Source

Both || and && force left to right operation. Both fully evaluate their LHS operand and apply any side effects before evaluating the RHS. Both short-circuit; if the result of the expression can be determined from the LHS, the RHS is not evaluated at all.

For ||, if the LHS evaluates to a non-zero value, then the RHS is not evaluated (true OR x is always true).

For &&, if the LHS evaluates to a zero value, then the RHS is not evaluated (false AND x is always false).

&& has higher precedence than ||, which has higher precedence than assignment, so the expression is parsed as

m = (++i || (++j && ++k ))

and evaluated as follows:

  1. ++i is evaluated first (|| forces left-to-right evaluation) and the side effect of incrementing i is applied;
  2. Since i is initially -3, ++i evaluates to -2;
  3. Since ++i evaluates to a non-zero value, the RHS expression ++j && ++k is not evaluated at all1;
  4. The result of an operation involving || or && is a boolean value (either 0 or 1) - since ++i is non-zero, ++i || ++j && ++k evaluates to 1;
  5. 1 is assigned to m.

So, by the time all of this is done, the following are true:

i == -2
j == 2  // unchanged
k == 0  // unchanged
m == 1

1. If ++i had evaluated to 0, then ++j && ++k would have been evaluated by evaluating ++j first, and if the result was non-zero, evaluating ++k.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download