gpt4 book ai didi

c - block 作用域标识符与静态存储持续时间的联系是什么?

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

我相信答案是没有链接,因为标准只保证具有静态存储持续时间的文件范围标识符具有内部链接。但是,对具有静态存储持续时间的标识符的函数的递归调用似乎不会为局部变量强加额外的内存。换句话说,在递归过程的任何阶段,标识符总是表示同一个对象 ,这很奇怪,因为它没有链接。这是为什么?

void recursive(void) {
static int a;
printf("%d", &a); // it repeatedly spits out the same address.
recursive();
}

最佳答案

局部静态变量没有链接(或者更准确地说,它们的链接没有)。来自 N1570(C11 草案)6.2.2 标识符的链接(强调我的):

6) The following identifiers have no linkage: an identifier declared to be anything other than an object or a function; an identifier declared to be a function parameter; a block scope identifier for an object declared without the storage-class specifier extern.



然而 static说明符强加此类变量具有静态存储持续时间,这是一种不同的事情。您所指的是对象的生命周期。此类变量表示对象,它们具有整个程序执行的生命周期,并且在概念上在程序实际启动之前被初始化一次。

6.2.4 元素存放期限:

2) The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

3) An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

关于c - block 作用域标识符与静态存储持续时间的联系是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879364/

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