Md. Rakibul Hassan Md. Rakibul Hassan - 1 year ago 72
C Question

Boolean expression with integer increments gives unexpected results

#include <stdio.h>
int main()
int x, y, z;
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download