Weird sum result [ANSWERED] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

13th May 2020, 12:42 PM
The_Fox
The_Fox - avatar
4 Answers
+ 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
13th May 2020, 1:12 PM
Avinesh
Avinesh - avatar
+ 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.
13th May 2020, 1:07 PM
Gen2oo
Gen2oo - avatar
+ 1
Thank you, very helpful indeed. So I could have used .at() instead of the []... interesting. I‘ll try that out.
13th May 2020, 1:18 PM
The_Fox
The_Fox - avatar
0
Alright, thanks. The random data makes sense :)
13th May 2020, 1:08 PM
The_Fox
The_Fox - avatar