3

I recently stumbled upon following code

int array[] = {10, 20, 30};
cout << -2[array];

I understand that array is a pointer to the first element of the array but then what does [pointer] means and then we write -2 in front of it which looks very alien to me.

ATK
  • 358
  • 3
  • 17
  • 3
    Refer to [With arrays, why is it the case that a\[5\] == 5\[a\]?](https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a) to explain why the array name and index can be swapped. – Sander De Dycker Oct 04 '19 at 09:49
  • 1
    Where do people keep finding this? – DeiDei Oct 04 '19 at 09:50
  • 1
    @DeiDei : evil code made to confuse people (as it did me for a minute, until I remembered how operator precedence is important here). – Sander De Dycker Oct 04 '19 at 09:55
  • 1
    @LDV: Important point, this happens only C and C++. In a language like Java or C#, it's a compilation error – Sisir Oct 05 '19 at 19:40
  • Yes, I just tried it in Java and it was a compilation error! Nevertheless I use only C, C++ and Python :) – ATK Oct 06 '19 at 14:50

3 Answers3

2

It is the same as if you'd write

cout << -(2[array]);

which is the same as

cout << -(array[2]);

In C++ operator [] on an array simply offsets the address of the array by the number specified in the brackets. As with any addition, you can swap operands and the result will remain the same.

For example -0[array] will give you -10 in this case.

Rinat Veliakhmedov
  • 1,021
  • 1
  • 19
  • 36
1

There are two ways to access an array element via a pointer offset. One is the common

int array[] = {10, 20, 30};
cout << -array[2]; // prints -30

and one is the unusual one that you posted. Both versions are equivalent.

Note that as the unary minus operator has a lower precedence compared to the subscript operator, -2[array] does not involve a negative index, but instead is the same as -(2[array]).

lubgr
  • 37,368
  • 3
  • 66
  • 117
0

In C and C++ the place of array name and the index can be swapped without changing the meaning i.e. -2[array] and -array[2] are the same. Both will compile and do the same thing. Check this SO post

However, if you try this in a language like C# or Java you will get a compiler error saying Cannot apply indexing with [] to an expression of type 'int' or something similar. This is a good example to understand how code works if the language supports pointers vs if it doesn't.

Note, as pointed out in the comment, negation operator has lower precedence over array index operator so it will compute to -array[2] instead of array[-2]

Sisir
  • 4,584
  • 4
  • 26
  • 37