3

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
CKM
  • 1,911
  • 2
  • 23
  • 30
  • Explain what you think this `if(0.0001<0.001<0.01)` does... – John3136 Dec 21 '15 at 05:04
  • that `0.001` lies in `(0.0001,0.01)`. period. – CKM Dec 21 '15 at 05:10
  • The original question doesn't explain what you mean by "works", what you expect or want to happen. You also don't explain what you mean by "why". Do you mean you don't understand what C++ is doing? Do you mean you do understand what C++ is doing, but you don't understand the motivation for C++ to work that way? etc. – bames53 Dec 21 '15 at 05:20
  • 2
    By "work", I meant I got the output in the 2nd case and no output in the first case(which is clearly writtien). I guess question is clear(had it not been clear, I have not got the right ans. below). Rather than down voting, you could have asked for clarification. – CKM Dec 21 '15 at 05:26

3 Answers3

9

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • I just found that `true<0.01` works in C++ but not in JAVA. Can you tell me why? It says that it cannot compare bool to float/double. – CKM Dec 21 '15 at 05:31
  • http://stackoverflow.com/questions/2015071/why-boolean-in-java-takes-only-true-or-false-why-not-1-or-0-also – joshp Dec 21 '15 at 05:42
0

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.

  • This is not compiler dependent. C++ specifies associativity so `a < b < c` will always evaluate as `(a < b) < c` – bames53 Dec 21 '15 at 05:22
0

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.

bames53
  • 86,085
  • 15
  • 179
  • 244