gpt4 book ai didi

c - 复杂函数定义中的参数范围

转载 作者:行者123 更新时间:2023-12-01 23:48:31 25 4
gpt4 key购买 nike

考虑以下模糊的函数定义,该函数返回指向 char 数组的指针:

char (*func(int var))[sizeof var]
{
return 0;
}

有效吗?

有问题的部分是在 sizeof 表达式中使用标识符 var。至少根据 GCC 4.9.2,varsizeof 表达式中不可见。 (请注意,如果将 sizeof 表达式中的 var 替换为例如 42,则该代码有效且此问题变得无趣。)

但是,在 C11 规范草案 n1570 中(相关部分在 C99 中是相同的,尽 pipe 条款编号可能不同),子条款 6.2.1 讨论了标识符的范围,并包含与这种情况相关的以下句子:

6.2.1p4 包含:

If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the end of the associated block.

6.2.1p7 包含(加粗我的):

Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

很明显,var 的声明符出现在函数定义的参数声明列表中。因此,根据 6.2.1p4,它的范围在函数体(“关联 block ”)的末尾结束。此外,var 显然对应于 6.2.1p7 中提到的“任何其他标识符”,因此它的作用域就在其声明符完成之后开始,即在参数列表的末尾。

在我看来,规范没有提及与 var 范围相关的其他内容。鉴于规范没有另外说明,对范围的“开始”和“结束”的明显(对我来说,无论如何)解释意味着范围跨越从开始到结束的整个词法区间。因此,似乎 var 实际上应该在 sizeof 表达式中可见。

规范中是否有我没有考虑到的内容?标识符的范围 的概念是否应该以某种不同于“从范围开始到范围结束的不间断词汇间隔”的方式来解释?如果是这样,这在规范中如何体现?

最佳答案

[sizeof var] 部分既不是 block 的一部分,也不是声明列表的一部分,而是返回类型的一部分。因此唯一可见的标识符是具有文件范围的标识符。

关于c - 复杂函数定义中的参数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827930/

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