Why is k not getting incremented whereas,i and j are getting incremented in the same expression.And i also want to know what is the output of the program.I am getting the output as
-2 3 1 0
#include <stdio.h>
void main()
{
int i=-3, j=2, m, k=0;
m=++i && ++j || ++k;
printf("%d %d %d %d", i, j, m, k);
}
The logical or,
||short-circuits, and afterthe value of the entire expression is determined, so the right operand of the
||isn’t evaluated.is parenthesized
m = (++i && ++j) || ++k;since the&&has higher precedence than the||.The short-circuiting of the logical operators means that the right operand is only evaluated when the evaluation of the left has not yet determined the final result, for
||that means the right operand is only evaluated if the left evaluated to 0, and for&&, the right operand is only evaluated if the left evaluated to a nonzero value.So first
++i && ++jis evaluated, and for that, first++iis evaluated.ihad the value-3before, so++ievaluates to-2, which is not 0, hence the++jis evaluated too.jhad the value2before, so++jevaluates to3, which is again nonzero, and thus++i && ++jevaluates to 1 (true). Since the left operand of the||is not zero, its result is already determined (to be 1), and the right operand isn’t evaluated, thuskremains unchanged andmis set to 1.