Why is a condition like (0 < a < 5) always true?

前端 未结 4 930
庸人自扰
庸人自扰 2020-11-29 13:56

I implemented the following program in C

    #include 
    int main() 
    {
       int a  = 10 ; 
       if(0 < a < 5) 
       {
               


        
4条回答
  •  孤城傲影
    2020-11-29 14:26

    Unlike Python (which has operator chaining), C evaluates the condition as:

    (0 < a) < 5
    

    The result of (0 < a) is either 0 or 1, both of which are less than 5, so the overall condition is true.

    In C, a range test must be written:

    0 < a && a < 5
    

    Note that the Python script:

    for a in range(-1,7):
      if 0 < a < 5:
        print a, " in range"
      else:
        print a, " out of range"
    

    produces the output:

    -1  out of range
    0  out of range
    1  in range
    2  in range
    3  in range
    4  in range
    5  out of range
    6  out of range
    

    The 'equivalent' C program using the same if condition would, of course, produce the answer 'in range' for each value.

提交回复
热议问题