views:

100

answers:

2
#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;
}
+11  A: 

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.

AndreyT
Indeed, without a sequence point the consequent could be evaluated at the same time as the condition; then we would see side effects for consequents (or alternates) that weren't used.
configurator
+4  A: 

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

dpb
Are you kidding, it looks like a good homework problem to me. What does this do? Why?
TheJacobTaylor
Well, that is why i put the smiley face on that one. Mostly since it wasn't tagged "homework". :)
dpb
@dpb : No, it's not a homework question. This was asked in first round of a local coding contest and I marked UB as answer. :(
missingfaktor
Yes, I could believe that, thanks for sharing. I like questions like this, short and fun to work through, even if I get them wrong sometimes!
dpb