In C++, the usual way of determining if some value, x, is between two limits is to:
//This is (A)
double x = 0.0d;
double lower = -1.0d;
double upper = +1.0d;
if(x > lower && x < upper){
// Do some stuff
}
But today I discovered by accident that I can do this:
// This is (B)
double x = 0.0d;
double lower = -1.0d;
double upper = +1.0d;
if(lower < x < upper){
// Do some stuff
}
It seems to work fine, but I’ve never heard of this being done before, with “lower < x < upper”. Does this produce executable code as you would expect it to? IE, is (A) equivalent to (B)?
I think a lot of people won’t know about this, and I suspect that might be because the compiler interprets (A) differently to (B). It this right?
No, A and B are not equivalent, you cannot do this.
Or, obviously you can (as you discovered) but you’re not doing what you think you’re doing.
You’re evaluating
(lower < x) < upper, i.e. the value oflower < x(which isfalseortrue, but which convert tointfor the comparison) is compared toupper.See this table of operator precedence for more information.