What is the difference between a variable declared as an auto
and static
?
What is the difference in allocation of memory in auto
and static
variable?
Why do we use static
with array of pointers and what is its significance?
views:
119answers:
2I'll assume if you're talking about auto
variables you probably mean local variables in a function. auto
is the default, it means the variable is allocated on the stack when the function is called and deallocated when the function returns. static
means the variable is allocated once the first time the function is called, and stays allocated for the rest of the program. This means:
int foo() {
static int x = 0;
return x++;
}
printf("%d\n", foo()); // Outputs 0
printf("%d\n", foo()); // Outputs 1
printf("%d\n", foo()); // Outputs 2
AUTO (default), Static, Extern & Register are the 4 modifiers for a variable in C.
- AUTO : Default. Normal Variable.
- STATIC : Changes the lifetime of the variable. (retains the scope, no change).
This means, during runtime, the OS does NOT of delete the variable from memory once the function( containing the variable exits) and initialise the variable every time the function is called.
Rather the static variable is initialised ONLY the first time the function (containing it is called). Then it continues to reside in the memory until the program terminates. in other words STATIC effectively makes a variable GLOBAL in memory, but with only LOCAL access.
Where your statics are stored depends on if they are 0 initialized or not.
0 initialized static data goes in .BSS (Block Started by Symbol),
non 0 initialized data goes in .DATA
One must note that, though static-variables are always in the memory, they can only be accessed ONLY from the local scope (function they are defined in).
en.wikipedia.org/wiki/External_variable#Scope.2C_lifetime_and_the_static_keyword
EXTERN : Used to signal to the compiler that the extern-definition is simply a placeholder, and the actual definition is somewhere else. Declaring a variable as extern will result in your program not reserving any memory for the variable in the scope that it was declared. It is also common to find function prototypes declared as extern.
REGISTER : Signals the compiler to Preferrably used a CPU-register (and not RAM) to store this variable. Used to improve performance, when repeated access to the variable is made (for ex: loop counter variables).