0

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.

Khuram
  • 53
  • 4

3 Answers3

7

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)
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • A somewhat technical clarification: precedence and grouping are independent notions. Most binary operators group left-to-right, which is why `x < y < z` means `(x < y) < z` as in this example. Assignment operators group right-to-left, so `a = b = c` means `a = (b = c)`. In the language definition, the definition of the operator includes a specification of its grouping behavior. +1 for the right answer. – Pete Becker Nov 05 '18 at 16:27
  • @PeteBecker i have to admit, this is the first time i hear about "grouping". Can you give a reference (if possible not the standard itself aka something human readable) ? – 463035818_is_not_an_ai Nov 05 '18 at 17:35
  • @user463035818 -- sorry, but that's all from the standard. People usually talk about precedence and associativity, but neither term is defined in the standard. Precedence falls out from the way the operators are defined in the grammar. Associativity is probably equivalent to grouping, but I haven't looked into it. – Pete Becker Nov 05 '18 at 18:08
2

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 ) 
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

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.

Vladimir Berezkin
  • 3,580
  • 4
  • 27
  • 33