Double comparison

后端 未结 3 1095
轮回少年
轮回少年 2021-01-29 03:21

Can I do this in C++?

if (4<5<6)
 cout<<\"valid\"<

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

boo         


        
相关标签:
3条回答
  • 2021-01-29 04:03

    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.

    0 讨论(0)
  • 2021-01-29 04:04

    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.

    0 讨论(0)
  • 2021-01-29 04:10

    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;
    }
    
    0 讨论(0)
提交回复
热议问题