gpt4 book ai didi

c - 复合语句( block )是否被 ANSI C 中的括号表达式包围?

转载 作者:行者123 更新时间:2023-12-04 12:32:52 25 4
gpt4 key购买 nike

浏览我找到的 Linux 内核源代码 some piece of code其中被括号包围的语句 block 被视为表达式 a la lisp(或 ML),也就是说,表达式的值是最后一条语句的值。

例如:

int a = ({
int i;
int t = 1;
for (i = 2; i<5; i++) {
t*=i;
}
t;
});

我一直在查看 ANSI C grammar试图找出这段代码如何适合解析树,但我没有成功。

那么,有人知道这种行为是标准强制要求的还是只是 GCC 的一个特性?

更新:我尝试使用标志 -pedantic,编译器现在给我一个警告:

warning: ISO C forbids braced-groups within expressions

最佳答案

这不是标准的 C。它是一个名为 statement expressions 的 gcc 扩展。 .您可以找到 C 扩展的完整列表 here .这实际上是 many gcc extensions used in the Linux kernel 之一看起来像clang supports this too尽管它没有在文档中明确命名。

如您所见,最后一个表达式用作表达式的值,文档说(强调我的):

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)

其中一个主要好处是制作安全 宏,避免对具有副作用的参数进行多次求值。给出的示例使用了这个不安全的宏:

#define max(a,b) ((a) > (b) ? (a) : (b))

它对 ab 求值两次,可以使用如下语句表达式重写以消除此问题:

#define maxint(a,b) \
({int _a = (a), _b = (b); _a > _b ? _a : _b; })

请注意,需要显式使用 int 可以使用另一个 gcc 扩展来修复 Typeof :

#define max(a,b) \
({ typeof (a) _a = (a), _b = (b); _a > _b ? _a : _b; })

请注意 clang also supports typeof .

关于c - 复合语句( block )是否被 ANSI C 中的括号表达式包围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59920282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com