考虑以下代码:
int i, k, m;
k = 12;
m = 34;
for (i = 0; i < 2; i++) ((i & 1) ? k : m) = 99 - i;
printf("k: %ld m: %ld\n\n", k, m);
在这个愚蠢的例子中,条件运算符表达式是一个快捷方式:
if (i & 1) k = 99 - i; else m = 99 - i;
我的编译器没有报错,执行这段代码给出了预期的输出
k: 98 m: 99
不过,我的问题是,根据 C 标准,这是否是有效代码?我以前从未见过类似的东西。
最佳答案
C11 标准中的脚注 110:
A conditional expression does not yield an lvalue.
和 6.5.16 第 2 段:
An assignment operator shall have a modifiable lvalue as its left operand.
所以不,该代码不符合 C 标准。
在 C++11 中,它是有效的:
If the second and third operands are lvalues and have the same type, the result is of that type and is an lvalue.
因此,这是 C 和 C++ 存在显着差异的另一个尘土飞扬的角落。如果您的编译器没有产生错误,那么我猜您正在使用具有“C 模式”的 C++ 编译器,而不是正确的 C 编译器; MSVC?
关于c - 条件运算符的有效使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10031392/