Why does the following piece of C code print 12 12 12
int main(int argc, char const *argv[]) {
int a = 2, *f1, *f2;
f1 = f2 = &a;
*f2 += *f2 += a += 2.5;
printf("%i %i %i\n", a, *f1, *f2);
return 0;
}
*f2 += *f2 += a += 2.5;
This line has Undefined Behavior because you change the value of *f2(i.e. a) more than once within the same expression without an intervening sequence point. UB means that your program may print "Hello World", it may crash, it may print 12 12 12 or 12 12 1029 or it may start eating your brains. Don't rely on undefined behavior.
To quote the C++ standard ( I know the question is tagged C, but I don't have a C standard by me and I know the same rule holds in C)
Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.
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