Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression evaluation in C

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;
}
like image 400
shreyasva Avatar asked Mar 12 '26 11:03

shreyasva


1 Answers

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

like image 115
Armen Tsirunyan Avatar answered Mar 14 '26 04:03

Armen Tsirunyan