在 C 中将增量应用于三元运算符
我认为三元运算符根据条件返回 :
左侧或右侧的值。为什么下面这段代码会打印 1?
#include <stdio.h>
int main(int argc, char const *argv[]) {
int c = 0;
(c?c:0)++;
printf("%i", c);
return 0;
}
I thought that the ternary operator returns either a value on the left side or the right side of :
depending on the condition. Why does this following piece of code print 1?
#include <stdio.h>
int main(int argc, char const *argv[]) {
int c = 0;
(c?c:0)++;
printf("%i", c);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能会遇到编译器错误,或者可能存在语言扩展,因为这不是有效的 C。您需要一个左值才能应用
++
运算符,并且(c?c :0)
不是左值。You would appear to have a compiler bug, or perhaps a language extension, since this is not valid C. You need an lvalue in order to apply the
++
operator, and(c?c:0)
is not an lvalue.我刚刚也遇到了一些与此相关的奇怪现象。在 gcc 3.3.2 中,三元条件的结果似乎可以被视为左值,但在 gcc 4.6 中则不行(我还没有准备好更多版本来进一步缩小范围)。事实上,不可能使用 gcc 4.6 编译 gcc 3.3.2,因为 gcc 4.6 对左值的构成更加挑剔。
gcc 3.3.2 源代码中的另一个示例不能使用 gcc 4.6 进行编译:
gcc 4.6 可以将强制转换的结果视为左值并递增它,但 gcc 4.6 不会。
我也没有相关的标准来确定这是官方标准中发生的变化还是海湾合作委员会在某个阶段允许的东西。
另请注意,C++ 允许三元运算符返回左值,但您仍然不能递增 0。因此,这是有效的 C++,但不是有效的 C:
I've just run across some oddness related to this, too. It seems that the result of a ternary conditional can be treated as an lvalue in gcc 3.3.2, but not in gcc 4.6 (I haven't got more versions ready to hand to narrow it down further). In fact it's not possible to compile gcc 3.3.2 using gcc 4.6 precisely because gcc 4.6 is much pickier about what constitutes an lvalue.
Another example from the gcc 3.3.2 source that doesn't compile with gcc 4.6:
gcc 4.6 could treat the result of a cast as an lvalue and increment it, but gcc 4.6 will not.
I also don't have the relevant standards to hand to find out of this is something that changed in the official standard or just something that gcc allowed at some stage.
Note also that C++ allows the ternary operator to return an lvalue, though you still can't increment 0. So this is valid C++ but not valid C:
仅仅因为你在做的事情
如果你不让“++”发生,你就会得到你想要的。
输出为:
gcc 版本 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
Simply because you are doing
If you don't let "++" happen, you will get what you want.
output is:
gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)