+ 2

I wanted the program to write it down the calculation, but a very large number just popped up and I don't understand the logic behind it: #include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4,5}; int sum = 0; for (int x = 0; x < 5; x++) { sum += arr[x]; cout<< sum << " + " << arr[x+1] << "="; } cout << sum; return 0; } //Outputs: 1 + 2=3 + 3=6 + 4=10 + 5=15 + 32766=15 Can someone tell me where do I get the 32766 from?

22nd Jun 2020, 1:14 PM
fergoka
+ 5
The variable x in the loop gets bigger than the array size (x becomes 4 in the last iteration and you go to arr[5] which doesn't exist), and so you point to a variable that isn't inside of the array. The new variable is some random number in memory, and each time you will run your program you will get a new random result (probably).
22nd Jun 2020, 1:20 PM
+ 3
Note what happens when x == 4: cout << sum << " + " << arr[4 + 1] ... You are accessing arr[5] which does not exist and is past the array boundary. So you get a random garbage value instead.
22nd Jun 2020, 1:21 PM
Schindlabua
+ 3
fergoka Most programming languages will throw an error in such a case but not C/C++ :) It's a feature, not a bug. C and C++ sacrifice safety for control and speed. Checking array boundaries on every access would take extra time so we don't do it. So you end up reading past the array in memory and you get to read what the last process wrote there. (or whoever owned that piece of memory before)
22nd Jun 2020, 2:56 PM
Schindlabua
+ 3
Exactly what Schindlabua said. In addition, when it comes to other languages like java/python, arrays are actually objects with attributes. So when you try to access an element that doesn't exist in the Object's context, it will give an error. Whereas in C/C++, arrays are simply stated as "continuous chunk of memory with the element is of specific size". So if you try to reach the element, you'l end up reaching whatever chunk of memory you encounter next..
22nd Jun 2020, 3:01 PM