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)?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With