Linux 中条件运算符的奇怪使用
在 3.0.4 Linux 内核中,mm/filemap.c 有这样一行代码:
retval = retval ?: desc.error;
我尝试使用 gcc -Wall 编译类似的最小测试用例,但没有收到任何警告;该行为似乎与以下内容相同:
retval = retval ? retval : desc.error;
查看 C99 标准,我无法弄清楚什么正式描述了此行为。为什么这样可以?
In the 3.0.4 Linux kernel, mm/filemap.c has this line of code:
retval = retval ?: desc.error;
I've tried compiling a similar minimal test case with gcc -Wall and don't get any warnings; the behavior seems identical to:
retval = retval ? retval : desc.error;
Looking at the C99 standard, I can't figure out what formally describes this behavior. Why is this OK?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他几个人所说,这是 GCC 扩展,而不是任何标准的一部分。如果您使用
-pedantic
开关,您会收到警告。在这种情况下,此扩展的点并不真正可见,但想象一下,如果使用
扩展,
foo()
仅被调用一次。如果没有它,您必须引入一个临时变量以避免调用 foo() 两次。As several others have said, this is a GCC extension, not part of any standard. You'll get a warning for it if you use the
-pedantic
switch.The point of this extension is not really visible in this case, but imagine if instead it was
With the extension,
foo()
is called only once. Without it, you have to introduce a temporary variable to avoid callingfoo()
twice.这是一个 gcc 扩展。
x ?: y
相当于x ? x : y
--- 请参阅 http://gcc.gnu。 org/onlinedocs/gcc/Conditionals.html#Conditionals。是的,我也觉得这很邪恶。
It's a gcc extension.
x ?: y
is equivalent tox ? x : y
--- see http://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals.Yes, I think it's evil too.
这是一个名为带有省略操作数的条件。省略中间操作数的效果是使用条件值作为省略的操作数,而无需再次对其求值。即使条件是宏,也可以安全使用。
This is a GCC extension called Conditionals with Omitted Operands. Omitting the middle operand has the effect of using the value of the conditional as the omitted operand without evaluating it again. It is safe to use even if the conditional is a macro.
这是 gcc 特定的 C 扩展,不是标准的。
This is a gcc-specific extension to C and is not standard.