Double comparison

喜欢而已 提交于 2019-12-02 20:04:41

问题


Can I do this in C++?

if (4<5<6)
 cout<<"valid"<<endl;

i.e a double comparison? Since I know that I can

bool a;
a = 1+2<3+4<5>6;//etc

回答1:


Yes, you can do it, but it won't be what you expect. It's parsed as

if ( (4<5) < 6 )

which yields

if ( 1 < 6 ) 

because 4<5 evaluates to true which is promoted to 1, which yields, obviously, true.

You'll need

if ( (4<5) && (5<6) )

Also, yes, you can do

a = 1+2<3+4<5>6;

but that as well is parsed as

a = ((1+2)<((3+4)<5))>6;

which will evaluate to false since (1+2)<((3+4)<5) yields a boolean, which is always smaller than 6.




回答2:


It compiles but won't do what you expect -

if( 4 < 5 < 2) 

same as

if( (4 < 5) < 2)

same as

if( (1 < 2) )  //1 obtained from cast to boolean

which is of course true, even though I imagine you were expecting something quite different.




回答3:


It may be clumsy but this will work:

int i, j, k;
i = 4; j = 5; k = 6;
if ( (i < j) && (j < k) )
{
    cout << "Valid!" << endl;
}


来源:https://stackoverflow.com/questions/12961717/double-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!