+ 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

2nd Nov 2018, 8:16 PM
mo🐼
mo🐼 - avatar
9 Réponses
+ 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.
2nd Nov 2018, 8:49 PM
Leif
Leif - avatar
+ 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
2nd Nov 2018, 8:56 PM
sneeze
sneeze - avatar
+ 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 👍
2nd Nov 2018, 9:09 PM
mo🐼
mo🐼 - avatar
+ 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.
2nd Nov 2018, 8:34 PM
Leif
Leif - avatar
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.
2nd Nov 2018, 8:26 PM
Leif
Leif - avatar
0
I am going to try that 👍
2nd Nov 2018, 8:36 PM
mo🐼
mo🐼 - avatar
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] = {};
2nd Nov 2018, 8:38 PM
Leif
Leif - avatar
0
YES! why is that! is it with the empty {} like we set it to zero!
2nd Nov 2018, 8:41 PM
mo🐼
mo🐼 - avatar
0
and with [] and empty {} it gave me a number 😮
2nd Nov 2018, 8:42 PM
mo🐼
mo🐼 - avatar