user2138149
user2138149

Reputation: 16559

Equalities in C/C++

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?

Upvotes: 2

Views: 432

Answers (4)

unwind
unwind

Reputation: 399753

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 of lower < x (which is false or true, but which convert to int for the comparison) is compared to upper.

See this table of operator precedence for more information.

Upvotes: 13

Pete Becker
Pete Becker

Reputation: 76245

It doesn't work fine. In fact, it's dead wrong, and only works by accident.

lower < x < upper is parsed as (lower < x) < upper; (lower < x) has type bool, and its value is either true or false, depending on the value of x. To compare that bool value to upper the compiler converts the bool to a float with the value 1.0 for true and 0.0 for false.

Upvotes: 1

Adri C.S.
Adri C.S.

Reputation: 3007

Well, yes. In either cases x is between the value range. For example: lower = 4; upper = 9; x = 7;

If you do: 7 > 4 && 7 < 9 is the same as saying 4 < 7 < 9. This is basic arithmetics, by the way.

Upvotes: -3

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

They are definitely not equivalent. Your expression lower < x < upper will first evaluate lower < x to either true or false, and then do true < x or false < x respectively.

Upvotes: 3

Related Questions