bahrep bahrep - 3 months ago 5
C Question

Logical OR operand evaluation basics in C

I'm learning C basics and I'm trying to understand why the output of this example is

1 2 1 1
:

int main()
{
int a, b, c, d;
a = b = c = d = 1;
a = ++b > 1 || ++c > 1 && ++d > 1;
printf("%d%d%d%d", a, b, c, d);
}



  • As far as I understand, only the left operand before Logical OR
    ||
    is getting evaluated because it is True and there is no need to evaluate the right one. The right operand is not evaluated. Is this right?

  • The left operand is true because
    ++b > 1
    equals
    1
    (2 is larger than 1) and
    a = 1
    . Right?


Answer

The left side of the || evaluates to true, and therefore the right side does not need to be evaluated. Hence, c and d remain 1, b is incremented to 2, and a gets assigned to true, which is promoted to 1.

Explanation:

a = b = c = d = 1;

All four variables equal 1.

a = ++b > 1

The variable b gets incremented to 2 before the rest of the RHS gets evaluated. This results in the expression 2 > 1, which is true. As others have mentioned, your || expression is then short-circuited, which means that what follows the || will not be evaluated because the program already knows that the entire RHS will be true regardless of what happens. This is why I did not bother to even write the expression ++c > 1 && ++d > 1, because it will be skipped.

And the variable a is set to true, which is the same as 1.

Reference on promoting true to int: Can I assume (bool)true == (int)1 for any C++ compiler?

Comments