[英](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
:我已经看到条件语法如下,在示例代码中显示了很多来检查整数值
y
是否在两个边界x
和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?
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
.我猜所有
x
, y
, z
都是一些整数类型,如int
或long
。 For floating point notice that NaN != NaN
.....对于浮点数注意
NaN != NaN
.....
The first if (x <= y <= z)
is wrong.第一个
if (x <= y <= z)
是错误的。 It is parsed as if ((x<=y) <= z)
.它被解析为
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).比较返回一个布尔值,当在某些整数上下文中使用时,该值被提升为 0(表示假)或 1(表示真)。 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)
因此,当
x <= y
,测试表现为if (1 <= z)
,相反,当x > y
,测试等价于if (0 <= z)
When asked to give all warnings (eg gcc -Wall
) a good compiler (such as GCC ) would warn you.当要求给出所有警告(例如
gcc -Wall
)时,好的编译器(例如GCC )会警告您。
Is the syntax allowable in ISO C?
ISO C 中是否允许使用该语法?
Read also Modern C and this C reference and the documentation of your C compiler.另请阅读Modern C和此C 参考以及 C 编译器的文档。 Study, for inspiration, the source code of existing open source software (eg on github or gitlab ).
研究现有开源软件的源代码(例如在github或gitlab 上)以获得灵感。 You are unlikely to see code such as
if (x <= y <= z)
.您不太可能看到诸如
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)
顺便说一句,在不太可能的情况下 - 我从来没有遇到过,但我从 1980 年代开始用 C 编写代码 - 你的意思是
if ((x<=y) <= z)
我觉得代码很奇怪,需要明确的评论,或代码if (((x<=y)?1:0) <= z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.