precedence of operators

Oct 20, 2012 at 5:33am
can anyone please explain me the output of the following??
I am not able to figure out why arent the values of b and c not incremented???
1
2
3
4
5
6
7
8
9
#include <stdio.h>
int main()
{
int a=10,b=12,c=13;
int d=++a||++b&&++c;
printf("%d\t%d\t%d\t%d",a,b,c,d);
getchar();
return 0;
}
Oct 20, 2012 at 5:49am
Try putting parentheses around every operator in the order the precedence table says they should be evaluated and see if that helps you figure out the expression.
Oct 20, 2012 at 8:00am
I am not able to figure out why arent the values of b and c not incremented???
It has nothing to do with precedence (syntax), and everything to do with semantics. Specifically, it's because of short-circuit evaluation.
Boolean OR (||) first evaluates its left hand operand (++a, in this case). If the operand is true (non-zero), the right hand operand (++b && ++c) is not evaluated, and the OR operation evaluates to true. Only if the left hand side is false is the right hand side evaluated.

This is because, if x is a boolean value,
(true || x) == true
(false || x) == x
Conversely,
(true && x) == x
(false && x) == false
Topic archived. No new replies allowed.