My understanding of static variables declared inside a function:
- If the initial value is not specified, the static variable will be in
.bss , otherwise in .data - Memory for statics is allocated along with globals - that is, long before execution enters
main- are these two assumptions correct ?
- When execution is started for the first time for the first time, the static is initialized by the value specified by the user (or zero if the initial value is not specified).
- ... and retain their values ββon subsequent function calls
But what if I declare my static variable inside the if block? I assume that my third point should be updated to "when the execution falls into the line where the static variable is declared, they are initialized ..." - am I right ?
Now, if the if block in which they are declared never hits (and the compiler can figure it out) - I understand that the variable will never be initialized; but is there any memory allocated for this variable?
I wrote two functions to try to figure out what is going on:
#include <stdio.h> void foo() { static foo_var_out; if(0){ static foo_var_in_0; printf("%d %d\n", foo_var_in_0); } else { static foo_var_in_1; printf("%d %d\n", foo_var_in_1); } } static void bar(int flag) { static bar_var_out; if(flag){ static bar_var_in_0; printf("%d %d\n", bar_var_in_0); } else { static bar_var_in_1; printf("%d %d\n", bar_var_in_1); } } int main() { foo(); bar(0); }
And I took an object dump:
$ gcc -o main main.c $ objdump -t main | grep var 45:080495c0 l O .bss 00000004 foo_var_in_1.1779 46:080495c4 l O .bss 00000004 foo_var_out.1777 47:080495c8 l O .bss 00000004 bar_var_in_1.1787 48:080495cc l O .bss 00000004 bar_var_in_0.1786 49:080495d0 l O .bss 00000004 bar_var_out.1785
From the output, it looks like foo_var_in_0 was not created at all (presumably because it is inside an explicit if(0) ), while bar_var_in_0 was created (how is it possible for the caller to pass a nonzero value value - although the only caller explicitly skips zero).
I assume that my question is: is it right to assume that no memory was allocated for the variable foo_var_in_0 ? I ask about this particular case; Am I reading objdump correctly - or do I need to do something else to check if the variable will occupy some memory during program startup?
In other words, if a line declaring a function-level static variable never hits, is the variable declared at all?
If it will not be created at all, does it comply with the C standard (less likely) or compile time optimization and at what level - how to turn it on or off (in gcc 4.1.1)?
I understand that one int is not a big deal to worry about, but I'm more interested in how this works; also, what if the variable was a large array of size, say, 5000 elements of a 10-byte structure?