#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", z);
}
This yields output as 6 whereas
#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y && z++;
printf("%d", z);
}
this would yield answer as 5. WHY ?? Someone please explain.
This is due to the Short Circuit mechanism.
What this means is that when the result of a logical operator is already determined, the rest of the expression isn't evaluated at all, including potential side effects.
The first code fragment behaves like:
int a = (1 && 0) /* result pending... */ || z++;
And the second:
int a = (1 && 0) /* result determined */;
This happens because the value of a logical AND is known to be false if the left side expression is false.