Reputation: 509
I have two C++ codes in which the one has an global int array while the other code has a local array whose length is determined by user input (so at runtime). Both arrays are not explicitly initialized.
#include <iostream>
using namespace std;
int M = 1000;
int a[M];
int main() {
for(int i = 0; i < M; i++)
cout << a[i];
cout << endl;
}
#include <iostream>
using namespace std;
int main() {
int M;
cin >> M;
int a[M];
for(int i = 0; i < M; i++)
cout << a[i];
cout << endl;
}
I observed that the global array is filled with zeros, while the local array (whose length is determined at runtime) is not filled with zeros and instead filled with a random numbers (but same at a time). I used the g++ compiler.
What is this behavior? Does C++ standard define this behavior?
Upvotes: 0
Views: 142
Reputation: 310980
From the C++ 17 Standard (11.6 Initializers)
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 (8.18). [ Note: Objects with static or thread storage duration are zero-initialized, see 6.6.2. — end note ]
So the array declared in the global namespace has the static storage duration and zero-initialized
While the array declared in main has the automatic storage duration and has indeterminate values of its elements.
Pay attention to that the variable length arrays is not a standard C++ feature.
int M = 1000;
int a[M];
or
cin >> M;
int a[M];
That is the both programs are not standard compliant.
And moreover variable length arrays may not be explicitly initialized in a declaration.
They can be supported by some compilers as their own language extensions.
Upvotes: 0
Reputation: 238351
What is this behavior?
The behaviour is that objects with static storage duration are zero-initialised before any other initialisation (if any).
The behaviour for all other storage duration is that there is no additional zero initialisation.
Does C++ standard define this behavior?
Yes, the zero initialisation of static objects is defined in the standard. The behaviour of reading indeterminate values is specified to be undefined.
Both programs are ill-formed because the size of an (non dynamic) array must be compile time constant, which M
is not.
Upvotes: 3