#include <iostream>
using namespace std;
struct A {
// Some Other Code
int x;
};
A a1;
int main(){
A a2;
cout << "a1.x = " << a1.x << endl;
cout << "a2.x = " << a2.x << endl;
return 0;
}
C++14 Standard (ISO/IEC 14882:2014) Section 8.5, Paragraph 12:
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. - end note ]
So does a1
have Static Storage Duration and does a2
have Automatic Storage Duration? The definition of Struct A
is at global namespace, as well as a1
declaration, while a2
declaration is at block scope (inside the main()
function).
Also, Section 3.6.2 says:
Paragraph 1:
Non-local variables with static storage duration are initialized as a consequence of program initiation.
Paragraph 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.
Besides, with gcc 5.4.0 I get a warning (warning: 'a2.A::x' is used uninitialized in this function [-Wuninitialized]
) and a random value, but with clang 3.8.0 the output is always a2.x = 0
(zero can also be an indeterminate value). I also made other more complex experiments, with nested struct
s and default initializations placed in // Some Other Code
. Sometimes I get random values and other times (not a negligible number of) I get a zero.
What is the Storage Duration of Struct
A
? And that of objectsa1
anda2
? And that of variablesa1.x
anda2.x
?Shoud
a1.x
anda2.x
be zero-initialized? Or are they indeterminate values?Do the same rules apply to
class
andunion
?Does it make any difference the code in
// Some Other Code
? For example, if a class T "has non-static members with default initializers" (like instruct A { int b = 1; int x; };
) then the default constructor can not be trivial (i.e. can not perform no action). Would that non-trivial constructor also initializex
? Trivial Default Constructor
Interesting links:
Initializing default values in a struct
Are members of a C++ struct initialized to 0 by default?
Default initialization of POD types in C++
Initialization of Objects with Static Storage Duration in C vs C++