I'm learning about static
variables in C and got to know that memory for static
variables is allocated at compile time (how much memory has to be allocated and its virtual address is calculated during compile time and actual memory is allocated when program loads) in either data segment/.bss depending whether initialized or not
I have seen in some web site posts that since the size the object/variable will take is predefined based on the variable type, the memory is allocated at compile time. But I didn't understand the need of this in case of local static
variables that are defined in a function and whose scope is only within the function.
Consider the following code snippet:
void func()
{
static int i;
/*some logic*/
}
void func1()
{
static int data[10] = {1,2,3,4,5,6,7,8,9,10};
/*some logic*/
}
int main()
{
/*logic not involving func() and func1()*/
}
In this case, the functions func
and func1
are not at all invoked in the program, yet the memory for static
variables in those functions are allocated as soon as the program loads (from what I learnt) which is actually not used. So, with this drawback what's the use of allocating memory for local static
variables. Why can't the compiler allocate memory for them in the data segment when it goes through the function.
I have gone through stack overflow questions regarding this and couldn't get an exact answer Please help!!!