Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare a static variable in main?

Tags:

c

main

static

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

like image 729
nebuch Avatar asked Jul 19 '16 15:07

nebuch


People also ask

Why do we declare variables static?

A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere.

Can we declare static variable in main?

We cannot declare static variables in the main method or any kind of method of the class. static variables must be declared like a class member in the class. Because during compilation time JVM binds static variables to the class level that means they have to declare like we declare class members in the class.

Where should static variables be declared?

C++ Programming Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

What happens when you declare a variable as static?

When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will be shared by all objects.


2 Answers

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.

like image 89
dbush Avatar answered Sep 28 '22 04:09

dbush


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.

like image 34
cleblanc Avatar answered Sep 28 '22 04:09

cleblanc