I have a code below and wanted to know what could be output.What i would like to see how different compiler would interpret this particular piece of code.
int main()
{
int i = -1, j = 2, k = 0, m;
m = ++i || ++j && ++k;
printf("\n %d %d %d %d \n", i, j, k, m);
return 0;
}
Now the question is while handling this code would compiler go by the rule which says
This expresion can be seen as
m = ++i || (++j && ++k);as && has higher precedence over || and the result would be 0 2 0 1
or
This expresion can be seen as
m = ++i || (++j && ++k);but compiler still will try to short circuit. so it evaluates ++i, since it’s 1,(++j&&++k) >are not evaluated.so ans is 0 3 1 1
The expression
++i || ++j && ++kwill group like so due to precedence:One of the few rules C has about evaluation order of expressions is that the left-hand side of the
||and the `&& operators must execute before the right-hand side (for short circuiting). This is a non-optional language requirement.That means that
++ihas to be evaluated first. It will return0(it does not evaluate to1as you mistakenly mention in the question). Since that’s not enough to short circuit the||operation, the right side will need to be evaluated. A similar process will occur for evaluation the&&operator (and both sides of the&&operation will need to be evaluated).The resulting output will be:
regardless of the compiler. There is no undefined, unspecified, or implementation defined behavior evaluating that expression.
The expression
++i || ++j && ++kwill group like so due to precedence:One of the few rules C has about evaluation order of expressions is that the left-hand side of the
||and the `&& operators must execute before the right-hand side (for short circuiting). This is a non-optional language requirement.That means that
++ihas to be evaluated first. It will return0. Since that’s not enough to short circuit the||operation, the right side will need to be evaluated. A similar process will occur for evaluation the&&operator (and both sides of the&&operation will need to be evaluated).The resulting output will be:
regardless of the compiler. There is no undefined, unspecified, or implementation defined behavior evaluating that expression.
One way to get the output you mention in your question is to use the following expression instead:
In this case,
--ievaluates to-2and the short circuiting rule requires that the right side of the||operator not be evaluated. Sojandkare left alone.