bbcbbc1
bbcbbc1

Reputation: 95

How to understand the behavior of back to back operators?

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 :

  1. 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 ]
    
  2. 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

Answers (1)

John Bode
John Bode

Reputation: 123468

Both || and && force left-to-right evaluation. && has higher precedence than ||1, so a || b && cis 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.


  1. Precedence only controls how expressions are parsed (which operators are grouped with which operands) - it does not control the order in which expressions are evaluated.

Upvotes: 3

Related Questions