6

I met a strange way of the appeal to an element of the array and thought it`s a mistake but it works. Can you explain how it works?

#include <iostream>
int main()
{
  int a[] = {1,2,3,4};
  std::cout << 1[a];
}
EzR1d3r
  • 194
  • 9

2 Answers2

10

Expression a[b] is equivalent to *(a + b) so in your example we have:

1[a] which can be written as *(1 + a) which is the same as *(a + 1) which is finally the same as a[1]

Karol Samborski
  • 2,757
  • 1
  • 11
  • 18
  • 2
    According to my brain's most vexing parsing, the first sentence is "Expression `a[b]` is equivalent to `*(a + b)`" without the restriction "in your example", which is not necessarily true. For example, if `a` is a `std::vector`, `a[b]` is (usually) equivalent to `a.operator[](b)`, while `*(a + b)` does not compile. Still +1, though. :) – L. F. Feb 08 '19 at 07:06
  • You're right, the operator[] can be overloaded and then the above may not be true. – Karol Samborski Feb 08 '19 at 07:10
2
BaseAddr[ Offset ] = *( BaseAddr + Offset )
Offset[ BaseAddr ] = *( Offset + BaseAddr ) = *( BaseAddr + Offset )
break1
  • 137
  • 6