understanding +=

I am doing a test that help me understanding some concept of c++
I need to write the output of the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include <iostream>
using namespace std;
int val(int arr[], int j)
{
arr[j] += arr[arr[j]];
return arr[j];
}
int main()
{
int numbers[4] = {1, 1, 1, 1};
for (int i = 0; i < 4; ++i)
{
cout << val(numbers,i);
}
return 0;
}




the answer is: 2233

however I don't understand why.
the code (a += b) is equal to (a = a+b in math)

I think:
if i=2, arr[j]=number[2]
arr[j]=arr[j]+arr[arr[j]]
number[2]=number[2]+number[number[2]]
=1+number[1]
=2

but the ans is 3

so where do I understand wrongly?
can anyone explain it to me. Thank you.
I recommend you to run your program through a debugger. Set a breakpoint on line 5 and print the content of the array.

At the starting point the array is filled with 1, so you can simplify the expresion to arr[j] += arr[1];
Now, arr[1] starts with 1, but the function modifies to 2.
You end up having
1
2
3
4
arr[0] += 1 // -> 2
arr[1] += 1 // -> 2
arr[2] += 2 // -> 3
arr[3] += 2 // -> 3 
Topic archived. No new replies allowed.