Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator[] magic [duplicate]

Tags:

c++

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];
}
like image 353
EzR1d3r Avatar asked Feb 08 '19 06:02

EzR1d3r


Video Answer


2 Answers

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]

like image 65
Karol Samborski Avatar answered Nov 04 '22 09:11

Karol Samborski


BaseAddr[ Offset ] = *( BaseAddr + Offset )
Offset[ BaseAddr ] = *( Offset + BaseAddr ) = *( BaseAddr + Offset )
like image 28
break1 Avatar answered Nov 04 '22 07:11

break1