Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the output of this C code compiler dependent?

#include <stdio.h>

int main(void)
{ 
   int a = 0, b = 1;
   a = (a = 5) && (b = 0);
   printf("%d", a);
   printf("%d", b);
}

The value of variable a is getting updated twice, which violates the C standards. So I think it will be compiler dependent. My I ran this code in lot of online C compilers and all are giving same output.

like image 851
SUBHAJIT PAUL Avatar asked Oct 15 '25 09:10

SUBHAJIT PAUL


1 Answers

The behavior of this code is well defined due to the sequence point introduced by the && operator. This is spelled out in section 6.5.13p4 of the C standard regarding the logical AND operator &&:

Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

Going through the code:

a = (a = 5) && (b = 0);

The left side of the && operator, i.e. (a = 5) is evaluated first, which sets a to 5. This evaluates to true, so there is then a sequence point before the right side, i.e. (b = 0) is evaluated. This sets b to 0 and evaluates to false, so the && operator results in the value 0. This value is then assigned to a.

like image 78
dbush Avatar answered Oct 18 '25 04:10

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!