How a single variable with two relational operators works internally

415 views Asked by At

We usually use logical operators if need to combine boolean expressions. I was wondering about the expressions if don't use logical operators.

int x=101;
if(90<=x<=100)
  cout<<'A';  

This code still prints 'A' on console. Can you please help me to understand that how and in which order this boolean expression would be evaluated.

3

There are 3 answers

0
463035818_is_not_an_ai On

This is a common source of errors, because it looks right, and sytactically it is correct.

int x=101;
if(90<=x<=100)

This is equivalent to

if (  (90 <= x) <= 100) 

which is

if ( true <= 100 )

and as true can convert to 1 this is

if ( true ) 
3
François Andrieux On

Since the operators have equal precedence, the expression is evaluated left-to-right :

if( (90 <= x) <= 100 )

if( (90 <= 101) <= 100 ) // substitute x's value

if( true <= 100 ) // evaluate the first <= operator

if( 1 <= 100 ) // implicit integer promotion for true to int

if( true ) // evaluate the second <= operator

To achieve the comparison you want, you would use the condition :

if( 90 <= x && x <= 100)
0
Vladimir Berezkin On

This expression is roughly equals to

int x=101;
bool b1 = 90 <= x; // true
bool b2 = int(b1) <= 100; // 1 <= 100 // true
if(b2)
    cout<<'A';

So here is true result.