简体   繁体   English

LOCAL static 变量何时初始化

[英]When are LOCAL static variables initialized

I keep on seeing the same sentence that static variables are initialized only once, and I also saw a sentence stating that "when the block is entered for the first time".我一直看到static变量只初始化一次的同一句话,我还看到一个句子说“第一次进入块时”。

Are local static variables initialized like other global variables - at the start of program execution?本地 static 变量是否像其他全局变量一样在程序执行开始时初始化? Or do local static variables differ from normal globals, and only get initialized once their function/block is called/reached?还是本地 static 变量与普通全局变量不同,并且仅在调用/到达其功能/块时才被初始化?

C17 6.2.4 (3) C17 6.2.4 (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.一个 object 其标识符声明时没有存储类说明符_Thread_local ,并且具有外部或内部链接或存储类说明符static ,具有 ZA81259CEF8E959C62479D1D456E5D2 存储持续时间。 Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.它的生命周期是程序的整个执行过程,它的存储值只在程序启动之前初始化一次。

However, remember the as-if rule .但是,请记住as-if 规则 An implementation could wait to initialize the variable until the first call to the function, as a conforming program has no way to access its value before then, and so would not be able to tell the difference.实现可以等待初始化变量,直到第一次调用 function,因为在此之前符合标准的程序无法访问其值,因此无法区分。

If you have an implementation with extensions or implementation-defined behavior that do provide a way to access the variable before the first call to the function, then such an implementation ought to document whether you would see the initialized value in such a case.如果您的实现具有扩展或实现定义的行为,在第一次调用 function 之前确实提供了访问变量的方法,那么这样的实现应该记录在这种情况下您是否会看到初始化值。 In most cases I would expect the answer to be "yes".在大多数情况下,我希望答案是“是”。

The most common implementation I'm familiar with is to load the initial value from the executable, or to place it in a bss section that is zeroed at startup, just as is done for global or file-scope static variables.我熟悉的最常见的实现是从可执行文件加载初始值,或者将其放在启动时归零的bss部分中,就像对全局或文件范围static变量所做的那样。

Although implementation dependent, static variables - any scope - are initialized as the executable is loaded.尽管依赖于实现,但 static 变量 - 任何 scope - 在加载可执行文件时被初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM