#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;
}
views:
100answers:
2
+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
2010-02-27 04:57:50
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
2010-10-17 21:58:05
+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
2010-02-27 05:02:25
Are you kidding, it looks like a good homework problem to me. What does this do? Why?
TheJacobTaylor
2010-02-27 05:05:59
Well, that is why i put the smiley face on that one. Mostly since it wasn't tagged "homework". :)
dpb
2010-02-27 05:13:12
@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
2010-02-27 05:16:36
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
2010-02-27 05:20:08