0
int n = 5;    
if(2<=n<=20) 
 {
  cout << "hello";
 }

In the above code, it does not give an error, it runs successfully and gives "hello" as output.

But we have to use && in this kind of equation.
Can anyone explain this?

Bharat Arya
  • 119
  • 1
  • 8

4 Answers4

12

<= is left-associative in C++, so the expresion is parsed as ((2 <= n) <= 20). 2 <= n is of type bool, which can implicitly convert to int: true converts to 1 and false converts to 0.

Both of these are <= 20, so the condition is effectively always true.


Note that the above assumes n is an int or another primitive numerical type. If n is a user-defined class with operator <= overloaded, the associativity bit is still true, but the part about implicit conversions may or may not apply, based on the return type and semantics of that overloaded operator.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
2

2<=n<=20 will be executed as (2<=n)<=20.

2<=n results in 0 or 1, depending on the value of n.

0<=20 and 1<=20 are true, so the cout will be executed, independent of the value and type of n.

n could be an object of a class with overloaded operators where 2<=n results to something (object to a class or a value >21), which compared with <=20 results to false. In this case there would be no output.

mch
  • 9,424
  • 2
  • 28
  • 42
1

You probably mean

if (2 <= n && n <= 20) 

C++ and C group 2 <= n <= 20 as (2 <= n) <= 20; the sub-expression is either 0 (false in C++) or 1 (true), which are both less than or equal to 20, hence the entire expresion is 1 (true). This is true for any primitive non-pointer type n, including a floating point NaN.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The first comparison 2 <= n is evaluated first. This returns true, which is convertible to an int. From conv.integral#2:

If the source type is bool, the value false is converted to zero and the value true is converted to one.

Once true is converted to 1 or 0, the next comparison is 1 <= 20 or 0 <= 20 which is always true. Hence the output.

lubgr
  • 37,368
  • 3
  • 66
  • 117