Search code examples
cstaticprogram-entry-point

Why declare a static variable in main?


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)?


Solution

  • 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.