Well ... The first thing we have to have and mind here is that a vector is nothing more than a pointer to a particular region of memory.
When the line of code, int reais[10]
, is executed, 10 integers are allocated and the address of the first item is stored, only.
When you access a certain position of the vector, reais[6]
for example, what actually happens is that the program takes the address of the pointer, that is, the first value (element) and sums with the offset that you passed times the size of the die. That is, the memory address actually accessed is reais + 6*tamanho de um inteiro
(multiplication by data size is done implicitly, according to the type of the defined vector), where real is the address of the first element of the vector. In other words, what happens is: *(reais + 6)
. Notice that the dereference operator is used.
That being said, when you use the 6[reais]
notation, what happens is exactly the same as I described above. But now you change the order of the sum between the address and the offset, that is, *(6 + reais)
.
Since addition is a commutative operation, the result is the same and so we access the same memory address. Therefore, reais[6] == 6[reais]
.
This is because [] is an operator (so much so that in C ++ you can overload it).