Search code examples
coperator-keyword

how the precedence and associativity works in the following example?


int i=3,j=1,k=0,m;
m=++i || ++j && ++k;
printf("%d%d%d%d",i,j,k,m);

//output is 4 1 0 1enter code here //can anyone explain why k=0 and j=1 only


Solution

  • m = ++i || ++j && ++k; is grouped as m = ++i || (++j && ++k); since, && has higher precedence. But, they are evaluated from left to right.

    Since, ++i = 4, which a non-zero number, the right hand expression is not evaluated. I mean (++j && ++k) is not evaluated since, left hand expression result is non-zero.

    For A||B, if A = 1, then results is always 1, irrespective of the value of B.

    Since, the right hand expression is not evaluated, the values of j and k remain same.

    This feature is called "Short Circuit Evaluation".