I'm trying really hard to understand how this expression is evaluated in c even though I know the precedence and associativity of operators in c language
int i=-4,j=2,k=0,m;
m = ++i || ++j && ++k;
As far as I know the pre increment operators are evaluated first from left to right the the logical and is then the logical so the I value will be -3 the j value will be 3 the k value will be 1 and for m value its 1 but it seems that I'm mistaken.
I'm studying this for an upcoming exam and ill appreciate any help.
The part that you're possibly missing while trying to understand the logic behind the final values obtained is what is known as short circuiting in C.
A summary of what it is -
if the first operand of the || operator compares to 1, then the second operand is not evaluated. Likewise, if the first operand of the && operator compares to 0, then the second operand is not evaluated.
Going by the above rules, the unary operation on i (++i
) returns with 1 and hence the following operands of the ||
statement are essentially ignored. Therefore, the value of all other variables remains unaffected and m
receives the value 1
.