When are LOCAL static variables initialized

Viewed 60

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".

Are local static variables initialized like other global variables - at the start of program execution? Or do local static variables differ from normal globals, and only get initialized once their function/block is called/reached?

2 Answers

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. 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. 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.

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. 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.

Although implementation dependent, static variables - any scope - are initialized as the executable is loaded.

Related