Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static local variable address in C

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?

like image 273
foobarbaz Avatar asked Jan 01 '23 06:01

foobarbaz


2 Answers

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.

like image 150
melpomene Avatar answered Jan 11 '23 21:01

melpomene


There's very little difference between local statics 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.)

like image 45
PSkocik Avatar answered Jan 11 '23 20:01

PSkocik