Reputation: 51
So, if I do this:
int a[5];
The array will contain garbage values.
If I do this though:
int a[5] = {};
It will now contain all zeros even though we didn't really initialize any of those values with 0s.
So, what's happening here?
Upvotes: 0
Views: 35
Reputation: 21
see this for more info: http://www.cplusplus.com/doc/tutorial/arrays/
By default, regular arrays of local scope (for example, those declared within a function) are left uninitialized. This means that none of its elements are set to any particular value; their contents are undetermined at the point the array is declared.
But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. The initializer can even have no values, just the braces:
int a[5] = { };
This creates an array of five int values, each initialized with a value of zero
Upvotes: 2
Reputation: 385098
What do you mean "what's happening"? You just told us what's happening.
The second example zero-initialises the values, whereas the first does not!
It will now contain all zeros even though we didn't really initialize any of those values with 0s.
Yes, you did, by writing = {}
. That's what it means.
Upvotes: 0
Reputation: 9602
int a[5];
requests a contiguous block of memory sufficient to store 5 integers but does not perform any initialization.
int a[5] = {};
requests a contiguous block of zero initialized memory sufficient to store 5 integers.
See this SO question/answer.
Upvotes: 0
Reputation: 569
You're initializing it with 0's.
Similarly,
int a[5] = {1};
would mean that the first element is initialized with a 1, and the rest with 0's.
Upvotes: 0