开发者

Does the following code invoke Undefined Behavior?

开发者 https://www.devze.com 2022-12-21 21:47 出处:网络
#include <iostream> #include <cmath> #define max(x,y) (x)>(y)? (x): (y) int main() { int i = 10;
#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(开发者_JAVA技巧i++,++j);
  std::cout << i << "\t" << j << "\t" << k << std::endl;
}


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.


Well, there certainly are a lot of problems with it.

  • max is actually computing min
  • increment operators are doubled on whatever choice is selected since you are using a macro
  • using postfix/prefix increments is just thrown in to confuse, but doesn't have a lot of bearing on the problem.

This code will produce the same results each time run, so no, it's not undefined. At the cout:

i = 11
k = 7
j = 7

This sounds like a bad homework problem. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号