Jayant - 1 year ago 79

C Question

Please tell how to solve it by associativity and precedence:

`#include<stdio.h>`

int main()

{

int i=-3,j=2,k=0,m;

m=++i||+j&&++k;

printf("%d %d %d %d",i,j,k,m);

return 0;

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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:

`++i`

is evaluated first (`||`

forces left-to-right evaluation) and the side effect of incrementing`i`

is applied;- Since
`i`

is initially`-3`

,`++i`

evaluates to`-2`

; - Since
`++i`

evaluates to a non-zero value, the RHS expression`++j && ++k`

is not evaluated at all^{1}; - 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; `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
```

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