Reputation: 7065
Reading over someone else's code, I saw something syntactically similar to this:
int main(void) {
static int attr[] = {FOO, BAR, BAZ, 0};
/* ... */
}
Is this an error or is there some reason to declare a variable in main
static
? As I understand it static
prevents linkage and maintains value between invocations. Because here it's inside a function it only does the latter, but main
is only invoked once so I don't see the point. Does this modify some compilation behavior (e.g. preventing it from being optimized out of existence)?
Upvotes: 12
Views: 5464
Reputation: 3688
static also tells the compiler to store the data in .data section of memory where globals are typically stored. You can use this for large arrays that might overflow the stack.
Upvotes: 6
Reputation: 224082
Unless you're doing something very non-standard such as calling main
directly, there's little point in declaring local variables static
in main
.
What it is useful for however is if you have some large structure used in main
that would be too big for the stack. Then, declaring the variable as static
means it lives in the data segment.
Being static
also means that, if uninitialized, the variable will be initialized with all 0's, just like globals.
Upvotes: 11