tags:

views:

144

answers:

7

In mathematics, the notation 18 < age < 30 denotes that age must lie between the values 18 and 30. Is it possible to use this kind of notation in the if statement? For example, I've tried executing

if(18 < age < 30)

and I get wierd output, so it's not quite right. Is there a way to do this or so I simply have to write

if(age > 18) blah
else if(age < 30) same blah
+9  A: 

You can do:

if (18 < age && age < 30) blah
tibur
You got it. Might mention that `if( 18 < age < 30)` is a legal C++ expression, and explain how it will be evaluated.
John Dibling
Manoj R
tibur
@tibur, still, it makes the code easier to read, and more malleable to vim's `ci(` :)
Alex B
I am with ManoJ R on adding braces. But I would do it for readability.
Martin York
@Manoj: In Lisp there is no confusion about operator precedence and therefore you don't need all those brack... ehm, never mind :)
Nemanja Trifunovic
@Nemanja - Never worked on Lisp (except small emacs scripts). But in lisp is it '18 < age' or '< 18 age'?
Manoj R
A: 

I know of no way to do exactly as you ask but the normal way is

Use the and operator

if (age > 18 && age <30)

Mark
A: 

Or write yourself a nice set of functions that does this

template <typename type>
bool in_range_[none|both|low|high]<type>( value, min, max )

to cater to all types of boundary included/or not

(don't use this for floating point)

In C++0x you could allow and disallow all other possibilities using the "delete" keyword that disables functions for overloads such as < float/double >

David
A: 

You can write a boolean expression as

((18 < age) && (age < 30))

An expression such as the above can be used whereever a boolean expression is acceptable, for example (but not limited to):

if((18 < age) && (age < 30)) { ... }

or

bool age_in_range = ((18 < age) && (age < 30));

Note that the above expression uses short-circuit evaluation of operator &&.

ArunSaha
if you are used to putting rvalues on the left hand side of operators, why not for also (age < 30)?
Chubsdad
I prefer to write the comparisons of numbers in the order they are on the number line. http://en.wikipedia.org/wiki/Number_line
ArunSaha
I would disagree with the notion that the above expressions "use short-circuit evaluation"; they do not rely on this behaviour.
Oli Charlesworth
May be I am wrong, but I thought if age is such that the first expression `(18 < age)` is `false`, then the second expression is not evaluated.
ArunSaha
@ArunSaha: You are correct, but as neither expression has any side-effects (assuming `age` is either a basic type or a class with a sane overload for `operator<`), this is completely irrelevant!
Oli Charlesworth
+3  A: 

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

Matthieu M.
A: 

Is it possible to use this kind of notation in the if statement?

Yes, possible.

Desirable, hardly ever: programmers presume the behaviours described in other answers will always apply, so if you dramatically change the order of evaluation and the meaning of an expression then it will really, badly confuse them and, sooner or later, cause grief. If you have a very small project with few staff, and they're basically looking to create a domain-specific language in C++, where the domain's notation is really much more readable and familiar using this notation (maybe their mathematicians not programmers anyway), then you might in extremis consider something like I present below, though it's still likely to cause trouble.

I've implemented this kind of thing before years ago as an academic exercise - if you wish to do so but need help getting started, and off the top of my head so doubtless buggy, consider:

struct Weird
{
    Weird(int n) : n_(n), b_is_meaningful_(false) { }
    Weird(int n, bool b) : n_(n), b_is_meaningful_(true), b_(b) { }

    int n_;

    bool b_is_meaningful_;
    bool b_;
};

Weird operator<(Weird lhs, Weird rhs)
{
    if (lhs.b_is_meaningful_)
        if (!lhs.b_) // effectively, anding with something already known false...
            return Weird(rhs.n_, false);
    return Weird(rhs.n_, lhs.n_ < rhs.n_);
}

Basically, you hack it around until you can:

Weird x = 10;
assert(6 < x < 20 < 30 < Weird(80));

At each point, the operator< creates a new Weird object with the Right Hand Side (rhs) value, while updating the boolean state on the assumption that you're effectively anding together a set of comparisons. If you really want to make a mess, you can support all kinds of things in C++, you might have a crack at say "x == 6 || 3 || 56" for fun...?

A: 

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)) { /****/ }
MSalters