+ 2
About an output
I am just interested in the output of this code isn't it supposed to be 4 or 5😮 https://code.sololearn.com/cf3CcnkoMQE1/?ref=app
9 odpowiedzi
+ 2
Yes. Without any size information (through either [] or {}) the compiler wouldn't know how large an array to create. It will either create none or, since "arr" exists, more likely set just arr[0] to 0...
But now may be a good time to search the web for a documentation on how initializer lists work exactly.
+ 2
https://code.sololearn.com/cL2Gx07xRdyg
Have a look at this code.
I added some output statements to make it clear.
int arr[5] = {}; should initialize the array to zero
+ 2
I checked it out the now it's official that the {} by default is 0😀
well and with a bit of Google Search I will understand the rest of how does {},[] working 👍
+ 1
That's right.
If you pulled the array out of main and made it global then it would be guaranteed to be initialized to zero. Then the output should be zero since you are adding only 0.
0
With that line sum += arr[x] you are adding the content of the first five array elements. But the array is uninitialized, so you are adding garbage value.
0
I am going to try that 👍
0
I also just noticed that an empty initializer list seems to be doing the same thing. That is, if you kept the array locally but wrote: int arr[5] = {};
0
YES! why is that! is it with the empty {} like we set it to zero!
0
and with [] and empty {} it gave me a number 😮