#include<stdio.h>
int main()
{
int i=-1, j=-1, k=-1, l=2, m;
m = (i++ && j++ && k++) || (l++);
printf("%d %d %d %d %d", i, j, k, l, m);
}
I am having confusions about how operator precedence is working in the evaluation of the logical expression in the given program.
The variable m
will be assigned 0
or 1
depending on the value of the logical expression that follows it.
The first parenthesis will be evaluated and the overall result of two AND operations will be true or 1
. But, since a short-circuit logical OR is used, the second parenthesis is not getting evaluated.
So, my question is if parentheses have higher precedence that all the other operators in that expression, why is not both the parentheses evaluated first, and then the OR operation performed?
That is, why is the output 0 0 0 2 1
and not 0 0 0 3 1
?
EDIT: What I have asked is somewhat different from this (suggested duplicate) as I am emphasizing on the parentheses enclosing the second operand of OR operator.
Operator precedence (and associativity) only determines how the expression should be parsed. It is a common mistake to confuse it with order of evaluation of the operands, which is different thing. Operator precedence is rather irrelevant in this example.
For most operators in C, the order of evaluation of the operands is not specified. Had you written true | l++
then l++
would have been executed. The "short-circuit evaluation" is the reason why this doesn't happen in your code. The && ||
operators is a special case, since they explicitly define the order of evaluation. The right operand of ||
is guaranteed not to be evaluated in case the left operand evaluates to non-zero.