0

Yesterday, I found this funny little piece of code:

#include <iostream>

int main()
{
   int a[2] = {1, 2};
   std::cout << 1[a];
   return 0;
}

And it runs, printing out the 2 to the console. I don't get why. My only idea that since a[1] is equal to *(a + 1), in theory we could swap the operations, so we would get *(1+a)=1[a]. But accepting the [] operator for a number still looks strange. Does anyone have an official answer to this question?

johnscapw
  • 1
  • 2
  • `a[i]` is the same as `*(a+i)` and that's the ssame as `*(i+a)`, and that leads to interesting deviance like `i[a]`. – user4581301 Jun 08 '22 at 21:18
  • That is the official answer. During parsing stages the C compiler will blindly convert `x[y]` to `*(x + y)`. As it turns out, this makes it easier to implement a compiler since it removes one potential factor to keep track of. C++ has a bit more going on behind the scene with operator overloading, but it mostly copies the same fundamentals. – Locke Jun 08 '22 at 21:20
  • 1
    A long long time ago in a computer far far away someone wrote a C compiler where `a[1]` was parsed into an AST as `* ( a + 1 )`. Some users quickly noticed `1[a]` turned into `* ( 1 + a )` and also worked. Years later when they wanted to standardize C they didn't want to break all the code out there using `1[a]` so they codified that `x[y]` is equivalent to `*(x+y)` regardless of what `x` and `y` are. – Goswin von Brederlow Jun 08 '22 at 21:20
  • Side note: Do yourself a favour and don't write code like that. One of the measures of the quality of a programmer is how rarely their name is used as a curse word by other programmers – user4581301 Jun 08 '22 at 21:22

0 Answers0