0

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?

KW123
  • 51
  • 2

4 Answers4

2

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

Vahid
  • 21
  • 3
  • So, if I do the same for a set of chars, will it take default values of chars? And what is a default value for a char? – KW123 Feb 22 '15 at 04:19
  • For array of chars if you do not specify any value in the braces, the default value will be '\0'. – Vahid Feb 22 '15 at 04:32
0

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.

Blob
  • 561
  • 1
  • 6
  • 19
0

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.

Community
  • 1
  • 1
James Adkison
  • 9,412
  • 2
  • 29
  • 43
0

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055