Checking if a value is within a range in if statment

后端 未结 2 520
忘了有多久
忘了有多久 2020-12-21 20:15

I did below:

if( \'0\' <= infix.at(i)<= \'9\'){
// some logic
}

Compiler gave me warning unsafe use of type \'bool\' in operation. I

相关标签:
2条回答
  • 2020-12-21 20:30

    As others have explained, the order of precedence groups the expression a <= b <= c into (a <= b) <= c, and the first part evaluated a <= b - is generally expected to return a boolean true/false value.

    Of course, if a and/or b are of a user-defined type, you can create a custom operator<= that returns a user-defined object rather than a boolean, and it can support the chaining you intend. (So, Amber's assertion "Some languages allow you to chain comparison operators, but C++ is not one of them." is untrue for user-defined types, but still good advise - see below). You can do chaining most easily at run-time (i.e. by returning an object that keeps a bool indicating the outcome of prior comparisons as well as a value forming the lhs for further chained comparisons), but it's also possible to do it using template expressions and gain efficient short-circuit evaluation.

    It's very rarely a good idea as other programmers won't expect your code to be evaluated that way. It'll confuse the hell out of them, and quite likely you when you come back to maintain the code after a few months, and likely lead to errors. No matter what, you can't support such ordering for non-user-defined types, and it's generally problematic to have such restrictions on how you can mix values in your expressions. No offense intended, but if you need to ask this question you're probably not ready to try implementing this or navigate the risks.

    0 讨论(0)
  • 2020-12-21 20:31

    The first version would be evaluated like this:

    if( ( '0' <= infix.at(i) ) <= '9' )
    

    which is why you get a warning about bool - you wind up with true/false <= '9' which doesn't make sense.

    Some languages allow you to chain comparison operators, but C++ is not one of them.

    0 讨论(0)
提交回复
热议问题