Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator | | in C [duplicate]

Tags:

c

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
like image 747
Ajo Mathew Avatar asked Feb 02 '26 03:02

Ajo Mathew


1 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.

like image 110
kaylum Avatar answered Feb 04 '26 01:02

kaylum