c++ – Why is the expression index[array] equivalent to array[index]?

Question:

Today I found a piece of code where the program seems to have a bug, but works as expected:

This is a simplification of that code, which reproduces the same behavior:

int main()
{
  int arreglo[] = { 0, 1, 2, 3 };
  int indice = 0;
  std::cout << arreglo[indice] << "\n";
  indice++;
  std::cout << arreglo[indice] << "\n";
  indice++;
  std::cout << indice[arreglo] << "\n";
  indice++;
  std::cout << arreglo[indice] << "\n";
}

Exit:

$ ./prueba
0
1
2
3

The question is: Why does the expression indice[arreglo] work as if I were putting arreglo[indice] , if they should be backwards?

Answer:

According to section 5.2.1 Subscripting of this working draft of the C++ standard (apparently the specifications are sold by the ISO and are not publicly available) E1[E2] is defined as

E1[E2] == *((E1)+(E2))

where E1 and E2 are any expression

Then

arreglo[indice] == *((arreglo) + (indice))

Therefore indice[arreglo] will be equivalent to:

indice[arreglo] == *((indice) + (arreglo))

By simple commutative property of addition we can see that both expressions give the same

In this case arreglo according to section 4.2 Array-to-pointer conversion is implicitly converted to the memory address of the first element of the array.

Scroll to Top