0
Weird sum result [ANSWERED]
If x < 9 (so the number is bigger than the actual number of array content, see loop), the output for sum when running the code changes constantly (sometimes to negative numbers!). Why is that the case?? https://code.sololearn.com/co4143IiDmCr/?ref=app
4 odpowiedzi
+ 1
It is an undefined behaviour.
It is explained well here with reasons.
https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why
+ 2
The memory accessed outside array bounds contains random data (or garbage) if that value is large it can overflow the integer and the signed bit is set (although overflow of signed integer types are undefined). That is why sum is sometimes negative. This would not happen for unsigned types.
+ 1
Thank you, very helpful indeed. So I could have used .at() instead of the []... interesting. I‘ll try that out.
0
Alright, thanks. The random data makes sense :)