wol*_*ats 3 c storage-class-specifier
天真的人可能认为它有,因为通常auto假设没有提供存储类关键字.
但是,对于放在auto它们前面的文件范围变量会产生错误.
#include <stdio.h>
auto int x;
int main(void){
x = 7;
printf("x = %d", x);
}
Run Code Online (Sandbox Code Playgroud)
Clang抱怨说:
3:10: error: illegal storage class on file-scoped variable
auto int x;
Run Code Online (Sandbox Code Playgroud)
声明x没有任何存储类关键字,它编译:
#include <stdio.h>
int x;
int main(void){
x = 7;
printf("x = %d", x);
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道x上面的例子中存储类有什么?它有名字吗?
关键字auto,static,extern,register,和_Thread_local被称为标准的存储类说明,但"对象"(这是我们通常所说的"变量"的standardese项)没有存储类.相反,它们具有链接(外部,内部,无)和存储持续时间(静态,自动,线程).此外,对象的任何声明可能是也可能不是定义.存储类说明符以及声明对象的作用域以及它是否具有初始值设定项(int foovs int foo = 3)控制这些属性.最简单的方法是展示它如何与表一起使用:
sc-specifier scope initialized linkage storage duration is a definition
------------ ----- ----------- ------- ---------------- ---------------
auto file no [constraint violation]
auto file yes [constraint violation]
auto block no none automatic yes
auto block yes none automatic yes
none file no external static yes
none file yes external static yes
none block no none automatic yes
none block yes none automatic yes
static file no internal static yes
static file yes internal static yes
static block no none static yes
static block yes none static yes
extern file no external static no
extern file yes external static yes
extern block no external static no
extern block yes external static yes
Run Code Online (Sandbox Code Playgroud)
术语"存储类说明符"有意地与术语"存储持续时间"和"链接"不同,以提醒您说明者不会让您独立控制存储持续时间和链接.
该语言不能让您独立控制存储持续时间,链接和定义,因为不可用的组合没有意义.自动存储持续时间仅对在块范围内声明的变量有意义,而不是定义仅对具有外部链接的变量有意义(因为只有它们可以在另一个文件中定义),依此类推.
我离开register,并_Thread_local出表的,因为他们是特殊的. register就像auto它除了它意味着你不被允许获取对象的地址. _Thread_local使变量的存储持续时间为"线程",不会改变链接; 它可以单独使用或与externor 一起使用static,但是将它与"auto"结合起来是违反约束的.如果你在块范围内单独使用它,我不确定它会做什么.
来自 C 标准 § 6.2.4 第 3 段:
如果对象的标识符是在没有存储类说明符 _Thread_local 的情况下声明的,并且具有外部或内部链接或具有存储类说明符 static,则具有静态存储持续时间。它的生命周期是程序的整个执行过程,并且其存储的值仅在程序启动之前初始化一次。
强调我的。向后参考§ 6.2.2 第 5 段:
如果函数标识符的声明没有存储类说明符,则其链接的确定与使用存储类说明符 extern 声明时完全相同。如果对象标识符的声明具有文件范围且没有存储类说明符,则其链接为 external。
再次强调我的。
因此,全局变量默认具有静态存储期限。即使没有标准来保证这一点,它也是唯一对全局变量有意义的存储持续时间类型。