Linux 中条件运算符的奇怪使用

发布于 2024-12-11 05:26:41 字数 272 浏览 2 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野味少女 2024-12-18 05:26:41

正如其他几个人所说,这是 GCC 扩展,而不是任何标准的一部分。如果您使用 -pedantic 开关,您会收到警告。

在这种情况下,此扩展的并不真正可见,但想象一下,如果使用

retval = foo() ?: desc.error;

扩展,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

retval = foo() ?: desc.error;

With the extension, foo() is called only once. Without it, you have to introduce a temporary variable to avoid calling foo() twice.

无风消散 2024-12-18 05:26:41

这是一个 gcc 扩展。 x ?: y 相当于 x ? x : y --- 请参阅 http://gcc.gnu。 org/onlinedocs/gcc/Conditionals.html#Conditionals

是的,我也觉得这很邪恶。

It's a gcc extension. x ?: y is equivalent to x ? x : y --- see http://gcc.gnu.org/onlinedocs/gcc/Conditionals.html#Conditionals.

Yes, I think it's evil too.

瑾兮 2024-12-18 05:26:41

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.

弃爱 2024-12-18 05:26:41

这是 gcc 特定的 C 扩展,不是标准的。

This is a gcc-specific extension to C and is not standard.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文