Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the expression -2[array] work? [duplicate]

Tags:

c++

c

I ran into this beauty, but I can't really understand it!

#include <iostream>

using namespace std;

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

  return 0;
}

It prints -30. Thank you in advance

Edit: Not a duplicate of this question because of the "-" sign.

like image 766
Aerozeek Avatar asked Jan 12 '16 17:01

Aerozeek


Video Answer


1 Answers

This is funny and simple. -array[2] is the 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 general case of using square brackets with arrays (With arrays, why is it the case that a[5] == 5[a]?), but the quirk here is the unary - operator in front.

It might seem intuitive to assume that the actual array index would be -2, like array[-2].

But this is not happening due to operator precedence rules:

  • operator [] has higher precedence than unary -, and as such is applied first.

I've shown the tranformation with 'conventional' array subscription to make this more intuitive

  • as we do not negate the array before subscripting it, we do not negate 2 the same way.
like image 78
SergeyA Avatar answered Sep 22 '22 06:09

SergeyA