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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With