7

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.

Community
  • 1
  • 1
Aerozeek
  • 495
  • 1
  • 3
  • 11

1 Answers1

12

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.
Community
  • 1
  • 1
SergeyA
  • 61,605
  • 5
  • 78
  • 137