0

Why does C++ allow the following statement?

  int a[10] = { 0 };
  std::cout << 1[a] << std::endl;
  std::cout << a[1] << std::endl;

Both lines print zero and no compiler warning is generated. Shouldn't 1[a] be illegal as 1 is not an array and a is not an integer type.

Code example : http://cpp.sh/4tan

Giuseppe Pes
  • 7,772
  • 3
  • 52
  • 90

2 Answers2

4

It is because of pointer arithmetic:

a[1] == *(a+1) == *(1+a) == 1[a];

Quoting the standard (§8.3.4; point 6):

Except where it has been declared for a class, the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.

Note that when you write a[1], the compiler interprets it as *(a+1). You are still referring the same array a when you write 1[a], so the compiler is infact still doing type checking.

abhishek_naik
  • 1,287
  • 2
  • 15
  • 27
1

Both are fine since under the covers it's all just pointer arithmetic. Taking the address of something and adding something else to it (a[1) is exactely the same as taking something else and adding an address to it (1[a]) - the final address of the object you refer to is the same. One notation is just more intuitive to humans than the other.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70