变量赋值比较

标签 c comparison-operators

抱歉,如果这是一个愚蠢的问题,但我找不到太多信息。 我只想将比较结果分配给一个变量,如下所示:

int a = 3, b = 2; // In actual code they're not integer literals
int result = a > b;

编译时,gcc(使用 -Wall)没有报错,查看汇编输出我发现它被翻译成 cmpsetle(或 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 yield 1 if the specified relation is true and 0 if it is false. The result has type int.

除非您要维护必须与 C99 之前的编译器兼容的遗留代码,consider using <stdbool.h> and bool type而不是 int .

关于变量赋值比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188903/

相关文章:

c - 修复 "undefined reference to"ft. makefile.txt 和 pthreads

C - 1/n 数之和

Powershell 无法精确匹配文件夹全名

comparison-operators - Overpass-api 比较运算符

c++ - 为什么 "!="与迭代器一起使用而不是 "<"?

c - 访问冲突读取位置 C 数组

c - C 中的 getfield(),不一致

python - 为什么 Python 中的表达式 0 < 0 == 0 返回 False?

php - "==="是什么意思?

c - 如何检查路径是否通向 c 中的目录之外?