简体   繁体   中英

(x <= y <=z) condition syntax in ISO C?

I've seen the condition syntax as follows, shown a lot in example code to check if an integral value y is between two bounds x and z :

if (x <= y <= z) { //... }

I thought I'd used this before myself, but in a small piece of code Im running a test on, the condition always evaluates to true... Doubting my own memory here now because I'm near sure I've used it before! Is the syntax allowable in ISO C? Am I just expecting it to do something it's not meant to do?

The old fashioned:

if (x >= y && x <= z) { //... } 

still works a charm so I haven't quite made it to the doddering stage of recall just yet ;)

I guess that all x , y , z are some integral type like int or long . For floating point notice that NaN != NaN .....

The first if (x <= y <= z) is wrong. It is parsed as if ((x<=y) <= z) . A compare returns a boolean value, which, when used in some integral context, is promoted to 0 (for false) or 1 (for true). So when x <= y the test behave as if (1 <= z) and when on the contrary x > y the test is equivalent to if (0 <= z)

When asked to give all warnings (eg gcc -Wall ) a good compiler (such as GCC ) would warn you.

Is the syntax allowable in ISO C?

Read also Modern C and this C reference and the documentation of your C compiler. Study, for inspiration, the source code of existing open source software (eg on github or gitlab ). You are unlikely to see code such as if (x <= y <= z) . That syntax is allowable, but weird.

BTW, in the unlikely case -I never meet that, but I do code in C since 1980s- you really mean if ((x<=y) <= z) I feel that the code is bizarre enough to need an explicit comment, or code if (((x<=y)?1:0) <= z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM