0

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.

1
  • storage is allocated for that at compile time. Commented Feb 17, 2014 at 20:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.