Logical operator | | in C

Viewed 116

I'm struggling to understand the behavior of the below code:

#include <stdio.h>

int main(void)
{
    int i;
    int j;
    int k;

    i = 7;
    j = 8;
    k = 9;
    printf("%d\n", (i = j) || (j = k));
    printf("%d, %d, %d\n", i, j, k);

    return (0);
}

Output:

1
8, 8, 9

Question:

  • I understand that expr1 | | expr2 has the value 1 if either expr1 or expr2(or both)has a nonzero value.

  • The value of i increased from 7 to 8 because j's value is assigned to i but the same way why does the value of the j is not increased even though j = k? I was expecting an

output

1
8, 9, 9
2 Answers

From the C standard (emphasis mine):

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

The above behaviour is commonly referred to as operator short circuiting.

In your example, since (i = j) is not zero the second operand is thus not evaluated.

First of all,

true || true is true

true || false is true

false || true is true

false || false is false

So operator || is calculating the first expression and if it is true, it does not check the second one.

In yours particular situation (i = j) is equal to 8, which is considered true, because int values are considered false only if they are equal 0. So the second (j = k) is never computed, which leads to your result.

Related