Multiple Relational Operators in a Single Statement

While studying C, I came across a peculiar problem that also persists in C++. The problem is mainly about using several relational operators within an expression without any logical operators.

Such usage was bugged and the expressions kept returning arbitrary results.Although bugged, I still wonder how the runtime handles such situations.

An example expression is such as:
if(a < b < c)

Expression-result couplings are such as following. The results are the values displayed when the expression is put into printf() or cout:

You may assume all of the expressions to be in cout as: cout << (a < b < c);

1
2
3
4
5
6
7
8
           //Output
1 < 2 < 3  //1
2 < 2 < 3  //1
3 < 2 < 3  //1
-3 < 2 < 3 //1
4 < 3 < 2  //1
3 < 2 < -3 //0
1 < 2 < 0  //0 


I'd appreciate help if anyone knows how such statements are handled.
You need to write your statements as follows

 
if(a < b && b < c)


This should get the results you expect.

My compiler displays

 
7:20: error: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning


Maybe turn up the warnings?
Let consider expression

1 < 2 < 3;

used in a C++ code.

It is calculated from left to right and the return type of a relational operator is bool.

So the expression can be rewritten as

( 1 < 2 ) < 3;

As 1 is less than 2 then the result of ( 1 < 2 ) is boolean value true. Then the next subexpression is calculated:

( true ) < 3;

Boolean value true is promoted to int and we get

( 1 ) < 3;

As 1 is less than 3 the result of the whole expression is true.

Let consider another expression

3 < 2 < -3;

Rewrite it

( 3 < 2 ) < -3;

Again after calculation of the first subexpression we get

( false ) < -3;

because 3 is not less than 2

false is promoted to int value 0 and we get

( 0 ) < - 3;

As 0 is greater than -3 then the result is false.

To correectly process these relational expressions you should write them as


1 < 2 && 2 < 3;

3 < 2 && 2 < -3;
Last edited on
The answers are all very helpful.

I just wanted to add, that the confusion is probably because the programming language looks a bit like some mathematics as the same symbols are used. But it has a different meaning.
For example, the = sign. In mathematics, we could write
x = x/2 + 3
That's an equation, we can solve it and get the result, x = 6.

But in C OR C++, the = sign means assignment of a value,
x = x/2 +3 ;
after execution, the value of x will depend on its previous value, and will change every time it is executed

OK, so I got off topic here. But my point is, don't mix up the meaning of symbols in mathematics with their meaning when programming.



The answers indeed were helpful. I had just missed the point of operation orders. Thanks.
Topic archived. No new replies allowed.