joe.ds
joe.ds

Reputation: 125

When is a local static variable stored in memory?

At what point does the language require the compiler to store a local static variable into memory? Is it at compile time? Or at runtime when the function that contains the local static variable is called?

int* GetMyVariable()
{
    static int A = 50;
    return &A;
}

I want to be able to only use memory for 'A' if GetMyVariable() is called. If static doesn't work like this, then is a dynamic allocation my only option? Thanks for your time.

Upvotes: 0

Views: 69

Answers (2)

Daniel Kamil Kozar
Daniel Kamil Kozar

Reputation: 19266

A static variable in C exists throughout the whole execution of a program. Therefore, you can safely take the address of that variable at any time.

Upvotes: 1

ouah
ouah

Reputation: 145829

When is a local static variable stored in memory

This is done prior to the execution of the program.

(C99, 6.2.4p3) "An object whose identifier is declared 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."

Upvotes: 1

Related Questions