抱歉,如果这是一个愚蠢的问题,但我找不到太多信息。 我只想将比较结果分配给一个变量,如下所示:
int a = 3, b = 2; // In actual code they're not integer literals
int result = a > b;
编译时,gcc
(使用 -Wall
)没有报错,查看汇编输出我发现它被翻译成 cmp
和 setle
(或 setg
等)。我想知道它是无效的 (C) 代码还是被认为是不好的做法,因为我发现它从未被使用过。
最佳答案
这是一个完全有效的 C 代码。该行为在 C99 标准的第 6.5.8.6 节中有详细说明:
Each of the operators
<
(less than),>
(greater than),<=
(less than or equal to), and>=
(greater than or equal to) shall yield1
if the specified relation is true and0
if it is false. The result has typeint
.
除非您要维护必须与 C99 之前的编译器兼容的遗留代码,consider using <stdbool.h>
and bool
type而不是 int
.
关于变量赋值比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188903/