gpt4 book ai didi

局部变量和寄存器变量可以声明为外部吗?

转载 作者:太空狗 更新时间:2023-10-29 16:46:36 26 4
gpt4 key购买 nike

我一直在想是否可以在本地声明一个extern和一个寄存器变量。如果可以的话,会施加什么限制?

最佳答案

局部变量在某些情况下可以声明为extern

让我们阅读 C99 N1256 standard draft .

标准将“局部变量”称为具有“ block 作用域”。

6.7.1/5“存储类说明符”说:

The declaration of an identifier for a function that has block scope shall have no explicit storage-class specifier other than extern.

然后对于将 extern 添加到局部变量的含义,6.2.2/4“标识符的链接”说:

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

让我们分解这些案例。

无需事先申报

void f() {
extern int i;
}

等同于:

extern int i;
void f() {}

除了声明仅在 f 内可见。

这是因为i 没有可见的事先声明。所以i有外部链接(和全局变量一样的链接)。

事先声明未指定链接

int i;
void f() {
extern int i;
}

等同于:

void f() {
extern int i;
}

因为前面的声明 int i 没有指定链接,因为第 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.

事先声明指定内部或外部链接

extern int i;
void f() {
extern int i;
}

等同于:

extern int i;
void f() {}

和:

static int i;
void f() {
extern int i;
}

等同于:

static int i;
void f() {}

因为在这两种情况下,我们分别有一个先前可见的外部和内部(static)链接声明。

初始化本地外部

无效的 C:

void f() {
extern int i = 0;
}

因为 block 范围声明有一个初始化。

有效 C:

extern int i = 0;
void f() {}

但可以说是糟糕的风格,因为相当于更短的:

int i = 0;
void f() {}

因为 6.7.8 初始化说:

If the declaration of an identifier has block scope, and the identifier has external or internal linkage, the declaration shall have no initializer for the identifier.

关于局部变量和寄存器变量可以声明为外部吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335742/

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