I know that a static local variable is in existence for the life of a program. But does a static local variable maintain the same memory address?
Or does the compiler just ensure that it exists and can be accessed within the local scope?
In C objects don't move around during their lifetime. As long as an object exists, it will have the same address.
Variables with static storage (this includes variables with block scope declared as static
) have a lifetime that covers the whole execution of the program, so they have a constant address.
There's very little difference between local static
s and regular globals.
int x = 42; //static lifetime, external name
static int y = 43; //static lifetime, no external name,
//referencable in all scopes here on out
//(unless overshadowed)
int main()
{
static int z = 44; //like y, but only referencable from within this scope
//and its nested scopes
{
printf("%p\n", (void*)&z));
}
}
All of these have fixed addresses once the program has been linked and loaded.
Local statics are like globals, except they're only referencable (by their name) from within their scope and its nested subscopes. (You can refer to them from unrelated scopes via pointers.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With