C Relational Operator Output

Srijan Kumar picture Srijan Kumar · Dec 27, 2015 · Viewed 9.2k times · Source
#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.

Answer

Amit picture Amit · Dec 27, 2015

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.