missingfaktor
missingfaktor

Reputation: 92116

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;
}

Upvotes: 4

Views: 192

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320787

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.

Upvotes: 12

dpb
dpb

Reputation: 1205

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. :)

Upvotes: 4

Related Questions