How does the expression -2 [array] work?

I came across this beauty, but I can not understand it!

#include <iostream> using namespace std; int main() { int array[] = {10, 20, 30}; cout << -2[array]; return 0; } 

He prints -30 . Thank you in advance

Edit: Do not duplicate this question because of the "-" sign.

+7
c ++ c
source share
1 answer

It is funny and easy. -array[2] same as -*(array + 2) , which is the same as -*(2 + array) , which is the same as -2[array] , which is -30.

There is already a duplicate for the general case of using square brackets with arrays ( With arrays, why is this: [5] == 5 [a]? ), But the quirk here is unary - operator in front.

It may seem intuitive to assume that the actual index of the array will be -2 , for example array[-2] .

But this does not happen due to operator precedence rules:

  • operator [] takes precedence over unary - , and as such is applied first.

I showed the transformation with the subscription "normal" to make it more intuitive.

  • since we do not deny the array before it is signed, we do not deny 2 in the same way.
+12
source share

All Articles