gpt4 book ai didi

c - 局部变量前的 GOTO

转载 作者:太空狗 更新时间:2023-10-29 16:24:52 32 4
gpt4 key购买 nike

以下代码是否构成未定义行为,因为我在变量声明之前跳转并通过指针使用它?如果有,标准之间是否存在差异?

int main() {
int *p = 0;
label1:
if (p) {
printf("%d\n", *p);
return 0;
}
int i = 999;
p = &i;
goto label1;
return -1;
}

最佳答案

您的程序中没有未定义的行为。

goto 语句有两个约束:

(c11, 6.8.6.1p1) "The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier."

您没有违反并且没有其他限制之外的要求。

请注意,它在 c99 和 c90 中是相同的(在没有额外要求的意义上)。当然,在c90中,由于声明和语句的混合,程序将无效。

关于在 goto 语句之后访问时 i 对象的生命周期,C 说(看我的重点,下面段落中的其他复制句子对于一个更棘手的程序):

(c11, 6.2.4p6) "For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. [...] If the block is entered recursively, a new instance of the object is created each time. [...] If an initialization is specified for the object, it is performed each time the declaration or compound literal is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached."

也就是说,当*p被读取时,i仍然存在;没有对象在其生命周期之外被访问。

关于c - 局部变量前的 GOTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005450/

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