Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

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

I implemented the following program in C

    #include <stdio.h>
    int main() 
    {
       int a  = 10 ; 
       if(0 < a < 5) 
       {
          printf("The condition is true!") ; 
       }
       return 0 ; 
    }

Why does the condition 0<a<5 always return true?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...