Comparing a variable to a range of values

Nobody answered as to what exactly happened with your code, so let me pick it apart.

Consider the single statement: bool result = 18 < age < 30;

We want to evaluate the right-hand expression: 18 < age < 30

There are two operators in this expression, and since they are identical, they both have the same priority, in this case, they are thus evaluated from left to right, therefore the expression is equivalent to:

(18 < age) < 30

So let's first examine the left-hand member: 18 < age, it yields a boolean which is either true or false, typically represented as an integral value respectively 1 or 0. Thus the expression can be summed up as:

{0,1} < 30

which is always true.

Therefore, should you use assert(18 < age < 30); it would never backfire.

This implicit conversion between integral (and floating point) built-in types is really annoying...


You can do:

if (18 < age && age < 30) /*blah*/;

A bit of template code can help here:

template <int min, int max> class range {
  static bool contains(int i) { return min <= i  && i < max; } // In C++, ranges usually are half-open.
};

int age = 23;
if (range<18,30>::contains(age)) { /****/ }