I tried the following code snippet:
void main()
{
int x = 1,y = 1,z = 1;
++x || ++y && ++z;
printf("x = %d\ny = %d\nz = %d\n",x,y,z);
}
The output I expected was:
x = 2
y = 2
z = 2
But I am getting the output:
x = 2
y = 1
z = 1
What is the reason for this?
This is because of short-circuiting.
http://en.wikipedia.org/wiki/Short-circuit_evaluation
When this is evaluated:
++x || ++y && ++z;
The first part ++x
already determines the value of the entire expression. So the ++y && ++z
is not executed at all. So the side-effects of ++y
and ++z
are not invoked.
The result of ++x
is nonzero, so evaluates to true, so short-circuits the ||
operator. ++y && ++z
is not executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With