I know that non-constant static variables need to be initialized outside the class definition but, is there a reason for this?
class A { static int x = 0 // compile error; static int y; }; int A::y = 0; // fine
In Java, static variables are also called class variables. That is, they belong to a class and not a particular instance. As a result, class initialization will initialize static variables. In contrast, a class's instance will initialize the instance variables (non-static variables).
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn't need any object.
But in some cases it generates code that uses two guard variables and initialize each static variable separately. The problem is when such two types of initialization are mixed in executable binary. In such case it may happen that second static variable will get initialized twice.
static or class variables (with an Object type) are initialized with null , because the compiler can't check if they are initialized at compile time. Instead of letting the program fail if it accesses a non-initialized variable, it will be initialized implicit with null .
Essentially it's because x
exists independently of the number of instances of A
that are created.
So storage for x
needs to be defined somewhere - you can't rely on an instance of A
to do that, and that's what
A::x = 0;
in exactly one translation unit, does.
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