Md. Rakibul Hassan Md. Rakibul Hassan - 11 days ago 5
C Question

Boolean expression with integer increments gives unexpected results

#include <stdio.h>
int main()
{
int x, y, z;
x=y=z=1;
z = ++x || ++y && ++z;
printf("%d, %d, %d", x, y,z);
return 0;
}


I am getting output 2, 1, 1. I need and explanation why Y is 1 in output?

Answer

The logical operation || is so-called "short-circuit" or "lazy" operation. If the left operand of such an operator is evaluating to logical true or a non-zero, the right operand won't be evaluated.

So in your case:

z = ++x || ++y && ++z; 

++x is evaluating to 2, making x equal 2. This is non-zero, so everything on the right side is not evaluated, so y and z are not incremented. And z is assigned by the result of the logical OR operation, i.e. 1. And this is what you see.

Comments