Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do non-constant static variables need to be initialized outside the class? [duplicate]

Tags:

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 
like image 670
Blasco Avatar asked Dec 19 '17 08:12

Blasco


People also ask

Why do we need to initialize static variables?

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

Do static variables need to be initialized?

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.

Can we initialize static variable twice?

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.

What controls the initial value of the non initialized static variables?

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 .


1 Answers

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.

like image 187
Bathsheba Avatar answered Sep 28 '22 09:09

Bathsheba