bahrep
bahrep

Reputation: 30662

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);
}

Upvotes: 1

Views: 133

Answers (4)

Sukhvinder Singh
Sukhvinder Singh

Reputation: 11

OR operator in c is the Logical operator. || Logical OR. True only if either one operand is true. In first line you assign 1 to all variables by a=b=c=d=1. After that, you are comparing conditions that a=++b>1 if it is true then the compiler will check the second condition that ++c>1 && ++d>1 this is with the && AND operator so in this if both equations are correct only then the command will run.

Upvotes: 0

Polaris000
Polaris000

Reputation: 938

The first line a = b = c = d = 1 assigns 1 to all variables as the associativity of the assignment operator (=) is from right to left.

Next: The concept to be applied here is called short-circuiting. The preference of '>' is higher than all the other operators except for the increment operator(++) -- the prefix increment to be precise.

Hence, first b gets incremented to 2. Now, the comparison of 2 > 1 occurs, which is true or 1. The left operand of the OR is true or 1. Thus, it hardly makes a difference if the right operand is true or false as the final output would still return true or 1.

Thus, everything to the right of the OR (||) isn't even evaluated. So c and d are not incremented and remain = 1.

a = True or 1 Thus a = 1, b = 2, c = d = 1

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522636

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?

Upvotes: 1

P.P
P.P

Reputation: 121427

Yes, you are right on both accounts.

The important to note is that this behaviour is guaranteed by the C standard and is commonly known as short circuting.

Relevant: Is short-circuiting logical operators mandated? And evaluation order?

Upvotes: 2

Related Questions