0

I'm just a beginner in C++. In my textbook it is stated that, "if the number of initial values is less than the size of the array, they will be stored in the elements starting from the first position and the remaining positions will be initialised with zero, in case of numeric data types." So I was just curious about the below two situations and was confused about the results:

1.

int num[5]={};
for(i=0;i<5;++i)
cout<<num[i]; //result: '00000'
int num[5];
for(i=0;i<5;++i)
cout<<num[i]; //result: some garbage values

In both the above cases, I didn't input any values to the elements (or I hope so). But why the second case didn't print zeros though?

4
  • 4
    In your second case, you do no initialisation. Commented Feb 23, 2023 at 17:21
  • 1
    The first one is called "value initialization". The values are set to 0 by default. In the second one, the values are uninitialized and random garbage remains. You can try the same with most types. Commented Feb 23, 2023 at 17:25
  • The second doesn't have an initializer with fewer initial values. It has no initializer at all, so nothing is initialized. Commented Feb 23, 2023 at 17:25
  • so, it means that it only works for value initialisation. Thank you gentle men, for teaching me something new today. It was so simple :) Commented Feb 23, 2023 at 17:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.