Does the following code cause 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; } 
+4
source share
2 answers

No, it is not.

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

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

No undefined here.

+12
source

Well, of course, there are a lot of problems.

  • max actually computes min increment operators
  • double for any choice since you are using a macro
  • using postfix / prefix increments is simply thrown to confuse, but doesn't really matter for the problem.

This code will give the same results every time it runs, so no, it's not undefined. In cout:

 i = 11 k = 7 j = 7 

That sounds like a bad home problem. :)

+4
source

Source: https://habr.com/ru/post/1302566/


All Articles