Reputation: 95
I'm having confusion using AND and OR though this is basic question I'm having lot of confusion. I understand there is short circuit methodology when AND and OR logical operators are being used.
Assume int a,x=0,y=0;
a). a= 10 && ++x && y++
Values a=0,x =1,y=1 [expected ]
b). a= 10 && ++x || y++
Values a=1 ,x=1,y=0 [short circuit
,expected ]
c). a= 10 || ++x || y++
Values a=1 , x=0, y=0 [short
circuit ]
My questions are :
a = 10 && y++
Values a =0, x=0(default didn't
change ), y=1 [ expected no short
circuit y is incremented later and
hence a =0 ]
With reference to question 1.
a = 10 || ++x && y++
Actual values :
a=1, x=0,y=0
What I expected :
a = 0, x=0, y=1
Explanation: 10 || ++x (short circuit )
So I remain with a = (1 && y++) => a=0 (no short circuit , and y has post increment) hence a =0,y=1.
How can I understand my question 2; I believe I missed something.
Upvotes: 1
Views: 80
Reputation: 123468
Both ||
and &&
force left-to-right evaluation. &&
has higher precedence than ||
1, so a || b && c
is parsed as a || (b && c)
. Remember that with a || b
, if a
is non-zero, then the result of the expression is 1 regardless of the value of b
, so b
is not evaluated at all. So in the expression a || (b && c)
, if a
is non-zero, then (b && c)
is not evaluated.
So, given a = 10 || x++ && ++y
, 10
is non-zero, meaning the result of the expression will be 1 regardless of the result of x++ && ++y
, so neither x++
nor ++y
are evaluated.
Upvotes: 3