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] << " "; } 
5
  • cplusplus.com/doc/tutorial/arrays Commented Jan 2, 2015 at 13:38
  • Why negative vote. I added the code snippet. Asked my doubt clearly. Don't know what SO is expecting from me. Commented Jan 2, 2015 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! Commented Jan 2, 2015 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. Commented Jan 2, 2015 at 14:30
  • I did search and could not understand and then I asked. Anyways point taken! :) Commented Jan 2, 2015 at 14:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
This is just a language construct. You can do what you want by std::fill_n.
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.
Because int arr[5]; is not initializing any elements.
But I did initialize it in 2nd line right? And I am using cout after second line.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.