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?
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?
<=
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.
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.
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.
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 valuefalse
is converted to zero and the valuetrue
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.