Behaviour of && in C programming language

Mayank Tiwari picture Mayank Tiwari · Aug 14, 2013 · Viewed 10.3k times · Source

I am beginner in C programming language, recently I have read about Logical AND && operator.

I also know that, in C programming language all non-zero values are treated as TRUE.

NON-ZERO && NON-ZERO = 1  
NON-ZERO && ZERO = 0  
ZERO && NON-ZERO = 0
ZERO && ZERO = 0  

But when I am dealing with the following program then I am not getting expected answer.

int main(){  
  int x, y, z;  
  x = y = z = -1;  
  y = ++x && ++y && ++z;  
  printf("x = %d, y = %d, z = %d, x, y, z);  
  return 0;  
} 

I am expecting

x = 0, y = 0, z = 0 

but the answer is

x = 0, y = 0, z = -1

Can anyone please explain, Why I am getting this answer?

Edit: In this question, I have not asked about the precedence of operators.

Answer

Maroun picture Maroun · Aug 14, 2013

Because of Short-circuit evaluation, when x is 0, y and z don't really need to be evaluated since 0 && ANYTHING is 0.

Once x is incremented to 0, the result is 0, and that's what y gets.

z remains unchanged (-1).


 x  | y  |  z 
----+----+-----
 -1 | -1 | -1   //x = y = z = -1;  
  0 | -1 | -1   //++x && ... Now the whole expression is evaluated to 0
  0 |  0 | -1   //y = ++x && ++y && ++z;