gpt4 book ai didi

c - 在作用域内,编译后(在 C 中)所有声明都发生在函数的开头吗?

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

在作用域内,编译后(在 C 中)所有声明都发生在函数的开头吗?下面的例子更好地展示了我的疑惑。如果“ptr1”出现问题,我是否可以假设 ptr2 已初始化为 NULL?

int main()
{
int ret = 0;

void * ptr1 = NULL;
if (ret = do_ptr_work(ptr1))
goto done;

void * ptr2 = NULL;
if (ret = do_ptr_work(ptr2))
goto done;

done:
if (ptr1) {
free(ptr1);
ptr1 = NULL;
}
if (ptr2) {
free(ptr2);
ptr2 = NULL;
}

return ret;
}

谢谢,
陈兹

最佳答案

不。初始化被定义为在达到声明时发生。如果跳过初始化,变量存在但未初始化。

C 标准的一个相关部分是 §6.2.4:

If an initialization is specified for the object, it is performed each time the declaration is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached.



(请注意,此文本仅适用于具有自动存储持续时间的对象)。另一个是§6.8:

The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.

关于c - 在作用域内,编译后(在 C 中)所有声明都发生在函数的开头吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4874654/

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