Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the following code invoke Undefined Behavior?

#include <iostream>
#include <cmath>

#define max(x,y) (x)>(y)? (x): (y)

int main() {
  int i = 10;
  int j = 5;
  int k = 0;
  k = max(i++,++j);
  std::cout << i << "\t" << j << "\t" << k << std::endl;
}
like image 254
missingfaktor Avatar asked Dec 06 '22 03:12

missingfaktor


1 Answers

No, it doesn't.

In this case the situation is saved by the fact the ?: operator has a sequence point immediately after evaluating the first operand (the condition) and after that only one of the two expressions (second or third operand) is evaluated. Your code is equivalent to

...
bool c = i++ > ++j;
k = c ? i++ : ++j;
...

No undefined behavior here.

like image 124
AnT Avatar answered Dec 28 '22 16:12

AnT