Can somebody tell me why the following does not work?(I mean no output)
if(0.0001<0.001<0.01)
cout<<"hi\n"<<endl;
output: (blank)
While the following works:
if(0.0001<0.001 && 0.001<0.01)
cout<<"hi\n"<<endl;
output:hi
Can somebody tell me why the following does not work?(I mean no output)
if(0.0001<0.001<0.01)
cout<<"hi\n"<<endl;
output: (blank)
While the following works:
if(0.0001<0.001 && 0.001<0.01)
cout<<"hi\n"<<endl;
output:hi
Because there is no magical n-ary <
operator in C++.
0.0001 < 0.001 < 0.01
is parsed (since <
is left-associative) as
(0.0001 < 0.001) < 0.01
and 0.0001 < 0.001
returns a value of type bool
with value true
. Now you have
true < 0.01
but according to the standard a true
boolean has value 1 when converted to an integral type so you have
1 < 0.01
which is false.
When you are using condition like
(0.0001<0.001<0.01)
It will check first 0.0001<0.001 i.e. true which returns 1 and now condition become
( 1< 0.01 )
which is false so returns 0 that's why printing nothing.
If you mean simply you don't understand what 0.0001<0.001<0.01
means or why it doesn't evaluate to what you expect: C++ only defines binary versions of the comparison operators. So 0.0001 < 0.001 < 0.01
is not a single comparison of all three values; it's a comparison of two values and then another comparison of the third value with the result of the other comparison. I.e. 0.0001 < 0.001 < 0.01
is the same as (0.0001 < 0.001) < 0.01
is the same as true < 0.01
is the same as 1 < 0.01
If you mean why didn't C++ define operators to work the way you want here, it's because nobody saw enough value in making C++ work that way.