0

I want to initialize all the array elements with just one value so I wanted to use option 1, the shorter version. But that does not seem to working. However option 2 works. Can anybody please explain what's going wrong when I try to initialize via option 1..

 int main()
    {
        int arr[5] = { 2 }; // option 1
        int arr1[5] = { 2, 2, 2, 2, 2 }; //option 2
        for (int i = 0; i < 5; i++)
            cout << arr[i] << " ";
        for (int i = 0; i < 5; i++)
            cout << arr1[i] << " ";
    }
Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • http://www.cplusplus.com/doc/tutorial/arrays/ – IdeaHat Jan 02 '15 at 13:38
  • Why negative vote. I added the code snippet. Asked my doubt clearly. Don't know what SO is expecting from me. – Unbreakable Jan 02 '15 at 13:38
  • Can some one explain why I got negative votes. I might have missed that duplicate question exists. And that is why DUPLICATE option is there to notify SO users. Why the negative notes! – Unbreakable Jan 02 '15 at 13:56
  • Without sounding rude, SO doesn't like it when people ask a question without doing basic research. In general, if the first google hit of the question gets you the answer, you'll probably get downvotes. – IdeaHat Jan 02 '15 at 14:30
  • I did search and could not understand and then I asked. Anyways point taken! :) – Unbreakable Jan 02 '15 at 14:32

1 Answers1

1
int arr[5] = { 2 };

You are providing initial value to first element only. In that case all elements are initialized by default to that type i.e 0 in your case.

ravi
  • 10,994
  • 1
  • 18
  • 36
  • I got your point, but it limits the use of array initialization right? Coz generally one in a million case we would want to just initialize the first value in an array leaving the rest to 0. Generally if we want our array to get initialized to a value, we would want the whole array to set to that particular value. Am I making sense? – Unbreakable Jan 02 '15 at 13:59
  • This is just a language construct. You can do what you want by std::fill_n. – ravi Jan 02 '15 at 14:01
  • Why the same syntax does not work when I split it in two lines. 'int arr[5];' `arr[5] = {-1};` . It starts giving garbage values. – Unbreakable Jan 02 '15 at 14:03
  • Because int arr[5]; is not initializing any elements. – ravi Jan 02 '15 at 14:04
  • But I did initialize it in 2nd line right? And I am using cout after second line. – Unbreakable Jan 02 '15 at 14:05
  • No, that's not an initialization. Refer to this http://stackoverflow.com/questions/10694689/how-to-initialize-an-array-in-c-objects – ravi Jan 02 '15 at 14:08