PROGRAM
#include <stdio.h>
int main(void)
{
int i, j, k;
i = 1; j = 1; k = 1;
printf("%d ", ++i || ++j && ++k);
printf("%d %d %d", i, j, k);
return 0;
}
OUTCOME
1 2 1 1
I was expecting 1 1 2 2. Why? Because the && has precedence over ||. So I followed these steps: 1) j added 1, so j now values 2... 2) k added 1, so k now values 2... 3) 2 && 2, evaluates to 1... 4) No need of further evaluation as the right operand of || is true, so the whole expression must be true because of short circuit behavior of logical expressions...
Why am I wrong?
Short circuiting is a functionality that skips evaluating parts of a (if/while/...) condition when able. In case of a logical operation on two operands, the first operand is evaluated (to true or false) and if there is a verdict (i.e first operand is false when using &&, first operand is true when using ||) the second operand is not evaluated.
Short-circuiting is one of the optimization steps of the compiler, in this step unnecessary calculation is avoided during the evaluation of an expression. Expression is evaluated from left to right.
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then − Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true.
Logical Expressions Logical expressions are a fundamental part of control statements, and programmers form them with combinations of two kinds of operators: It's not possible to understand or to effectively use control statements without a thorough understanding of logical expressions and the operators that form them.
Precedence affects only the grouping. &&
has a higher precedence than ||
means:
++i || ++j && ++k
is equivalent to:
++i || (++j && ++k)
But that doesn't mean ++j && ++k
is evaluated first. It's still evaluated left to right, and according to the short circuit rule of ||
, ++i
is true, so ++j && ++k
is never evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With