-2

I have the following code.that demonstrates the problem I am having. How come the comparison is not evaluating to true? Is this a limitation of integer and floating point comparisons?

#include <iostream>

int main(){

    double m = -0.625;
    if((-1)<=m<=0){
        std::cout << "Enter here" <<std::endl;
    }
    return 0;
}
Belphegor
  • 1,683
  • 4
  • 23
  • 44

3 Answers3

2

You can't do three way comparison like that in C. Change it to the following and it'll work:

if((-1) <= m && m <= 0){
        std::cout << "Enter here" <<std::endl;
    }
16tons
  • 675
  • 5
  • 14
0

The condition in this if statement

if( ( -1 ) <= m <= 0 ){

is equivalent to

if( ( -1 <= m ) < = 0 ){

as -1 is less than m then the subexpression ( -1 <= m ) yields 1 in C and true in C++ that then is converted to 1 and the subexpression 1 <= 0 yields 0 in C and false in C++..

To get the expected result you should write instead

if( -1 <= m  && m <= 0 ){
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

In C++ -1 <= m <= 0 is equivalent to (-1 <= m) <= 0.

In this example, -1 is implicitly converted to a float in order to use the <= operator with m. The result of this expression is a bool. This result is then implicitly converted to an int in order to use the <= operator with 0. Since a bool is converted to either 0 or 1 (false or true), this conditional statement will only be true when m is less than -1.

It makes sense from a math standpoint to structure the if statement like that, however you must break it up explicitly so the compiler knows what you want.

Try this

-1 <= m && m <= 0
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61