ATK
ATK

Reputation: 368

What's the meaning of -2[array]

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.

Upvotes: 3

Views: 2358

Answers (3)

Sisir
Sisir

Reputation: 5398

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]

Upvotes: 0

Rinat Veliakhmedov
Rinat Veliakhmedov

Reputation: 1039

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.

Upvotes: 2

lubgr
lubgr

Reputation: 38287

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]).

Upvotes: 1

Related Questions