When are static variables initialized?
From See Java Static Variable Methods:
- It is a variable which belongs to the class and not to object(instance)
- 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.
Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.
What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.
In case of inner classes, they can not have static fields
An inner class is a nested class that is not explicitly or implicitly
declaredstatic
....
Inner classes may not declare static initializers (§8.7) or member interfaces...
Inner classes may not declare static members, unless they are constant variables...
See JLS 8.1.3 Inner Classes and Enclosing Instances
final
fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final
fields. See the example below.
final class Demo
{
private final int x;
private static final int z; //must be initialized here.
static
{
z = 10; //It can be initialized here.
}
public Demo(int x)
{
this.x=x; //This is possible.
//z=15; compiler-error - can not assign a value to a final variable z
}
}
This is because there is just one copy of the static
variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z
of type static final
within the constructor, it will attempt to reinitialize the static final
type field z
because the constructor is run on each instantiation of the class that must not occur to static final
fields.
When are static variables initialized in Python?
Before.
The __init__
method isn't run until Foo
is instantiated. i=1
is run whenever the class definition is encountered in the code
You can see this by adding print statements:
print('Before Foo')
class Foo:
i = 1
print(f'Foo.i is now {i}')
def __init__(self):
print('Inside __init__')
self.i += 1
print(f'i is now {self.i}')
print('After Foo')
print('Before __init__')
foo = Foo()
print('After __init__')
which prints:
Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__
Notice however, that your self.i += 1
does not modify the class attribute Foo.i
.
foo.i # This is 2
Foo.i # This is 1
When do function-level static variables get allocated/initialized?
I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
};
test t("global variable");
void f()
{
static test t("static variable");
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
When are static and global variables initialized?
By static and global objects, I presume you mean objects with
static lifetime defined at namespace scope. When such objects
are defined with local scope, the rules are slightly different.
Formally, C++ initializes such variables in three phases:
1. Zero initialization
2. Static initialization
3. Dynamic initialization
The language also distinguishes between variables which require
dynamic initialization, and those which require static
initialization: all static objects (objects with static
lifetime) are first zero initialized, then objects with static
initialization are initialized, and then dynamic initialization
occurs.
As a simple first approximation, dynamic initialization means
that some code must be executed; typically, static
initialization doesn't. Thus:
extern int f();
int g1 = 42; // static initialization
int g2 = f(); // dynamic initialization
Another approximization would be that static initialization is
what C supports (for variables with static lifetime), dynamic
everything else.
How the compiler does this depends, of course, on the
initialization, but on disk based systems, where the executable
is loaded into memory from disk, the values for static
initialization are part of the image on disk, and loaded
directly by the system from the disk. On a classical Unix
system, global variables would be divided into three "segments":
- text:
The code, loaded into a write protected area. Static
variables with `const` types would also be placed here.- data:
Static variables with static initializers.- bss:
Static variables with no-initializer (C and C++) or with dynamic
initialization (C++). The executable contains no image for this
segment, and the system simply sets it all to `0` before
starting your code.
I suspect that a lot of modern systems still use something
similar.
EDIT:
One additional remark: the above refers to C++03. For existing
programs, C++11 probably doesn't change anything, but it does
add constexpr
(which means that some user defined functions
can still be static initialization) and thread local variables,
which opens up a whole new can of worms.
When are static C++ class members initialized?
The standard guarantees two things - that objects defined in the same translation unit (usually it means .cpp file) are initialized in order of their definitions (not declarations):
3.6.2
The storage for objects with static storage duration (basic.stc.static) shall be zero-initialized (dcl.init) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (basic.types) with static storage duration initialized with constant expressions (expr.const) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.
The other guaranteed thing is that initialization of static objects from a translation unit will be done before use of any object or function from this translation unit:
It is implementation-defined whether or not the dynamic initialization (dcl.init, class.static, class.ctor, class.expl.init) of an object of namespace scope is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or object defined in the same translation unit as the object to be initialized.
Nothing else i guaranteed (especially order of initialization of objects defined in different translation units is implementation defined).
EDIT
As pointed in Suma's comment, it is also guaranteed that they are initialized before main
is entered.
Why does a static variable initialized by a method call that returns another static variable remains null?
Static things gets executed in the order they appear in the code.
static String s1 = getVal();
So starting with first line, s1
gets evaluated and by that time s2
is still null
. Hence you see the null value.
When do static variables get initialized in C#?
Oh, that is complex. It depends on whether the beforefieldinit
flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be.
Frankly, I wouldn't code to any specific behaviour here; simply: static fields will be initialized before you try to use them, as long as you use regular code to access them.
Jon Skeet has a good write-up on this here and here
Initialize static variables in C++ class?
They can't be initialised inside the class, but they can be initialised outside the class, in a source file:
// inside the class
class Thing {
static string RE_ANY;
static string RE_ANY_RELUCTANT;
};
// in the source file
string Thing::RE_ANY = "([^\\n]*)";
string Thing::RE_ANY_RELUCTANT = "([^\\n]*?)";
Update
I've just noticed the first line of your question - you don't want to make those functions static
, you want to make them const
. Making them static
means that they are no longer associated with an object (so they can't access any non-static members), and making the data static means it will be shared with all objects of this type. This may well not be what you want. Making them const
simply means that they can't modify any members, but can still access them.
C++ static variables initialization order
The first scenario is well-defined in [basic.start.init]/2:
Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.
Constant initialization is performed:
- if each full-expression (including implicit conversions) that appears in the initializer of a reference with static or thread storage duration is a constant expression (5.19) and the reference is bound to an lvalue designating an object with static storage duration or to a temporary (see 12.2);
- if an object with static or thread storage duration is initialized by a constructor call, if the constructor is a
constexpr
constructor, if all constructor arguments are constant expressions (including conversions), and if, after function invocation substitution (7.1.5), every constructor call and full-expression in the mem-initializers and in the brace-or-equal-initializers for non-static data members is a constant expression;- if an object with static or thread storage duration is not initialized by a constructor call and if every full-expression that appears in its initializer is a constant expression.
Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place. (...)
(Emphasis mine)
The upshot of this fairly lengthy paragraph is that
int n = 2;
is static initialization, while
int k = n;
is dynamic initialization (because n
is not a constant expression), and therefore n
is initialized before k
even if it appears later in the code.
The same logic applies in the case of the Base::static_constructor
example -- because the constructor of Base::static_constructor
is not constexpr
, Base::constructor
is dynamically initialized, whereas Base::i
is statically initialized. The initialization of Base::i
therefore takes place before the initialization of Base::constructor
.
On the other hand, the second case with
int n = func();
puts you squarely in the territory of unspecified behavior, and it is quite explicitly mentioned in [basic.start.init]/3:
An implementation is permitted to perform the initialization of a non-local variable with static storage duration as a static initialization even if such initialization is not required to be done statically, provided that
- the dynamic version of the initialization does not change the value of any other object of namespace scope prior to its initialization, and
- the static version of the initialization produces the same value in the initialized variable as would be produced by the dynamic initialization if all variables not required to be initialized statically were initialized dynamically.
[Note: As a consequence, if the initialization of an object
obj1
refers to an objectobj2
of namespace scope potentially requiring dynamic initialization and defined later in the same translation unit, it is unspecified whether the value ofobj2
used will be the value of the fully initializedobj2
(becauseobj2
was statically initialized) or will be the value ofobj2
merely zero-initialized. For example,inline double fd() { return 1.0; }
extern double d1;
double d2 = d1; // unspecified:
// may be statically initialized to 0.0 or
// dynamically initialized to 0.0 if d1 is
// dynamically initialized, or 1.0 otherwise
double d1 = fd(); // may be initialized statically or dynamically to 1.0
-- end note]
Related Topics
How to Find the Currently Running Applications Programmatically in Android
How to Check Certificate Name and Alias in Keystore Files
Webview and Cookies on Android
Android: Sending Data >20 Bytes by Ble
How to Add Image in a Textview Text
What Is Shareduserid in Android, and How Is It Used
Android Studio Debugger Highlights the Wrong Lines
How to Pass a String from One Activity to Another
How to Change Color of the Back Arrow in the New Material Theme
How to Troubleshoot "Inconsistency Detected: Dl-Lookup.C: 111" (Java Result 127) Error
Javafx Freeze on Desktop.Open(File), Desktop.Browse(Uri)
How to Call a Stored Procedure from Java and JPA
Hibernate 5 :- Org.Hibernate.Mappingexception: Unknown Entity