-2

The following code

#include<stdio.h>

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

prints -30. How? Why?

Natasha Dutta
  • 3,102
  • 19
  • 23
  • 5
  • I humbly disagree with the dupe. This question involves a significant amount of difference, in terms with the operator precedence involved in it and misconception of UB, as shown in (now deleted) comments. I request a re-consideration for this case. – Natasha Dutta Jul 02 '15 at 15:33

3 Answers3

12

In your case,

 cout<<-2[arr];

gets translated as

cout<<-(arr[2]);

because,

  1. array indexing boils down to pointer arithmatic, so, the position of array name and the index value can be interchanged in notation.

    The linked answer is in C, but valid for C++ also.

  2. regarding the explicit ()s, you can check about the operator precedence here.

Community
  • 1
  • 1
Natasha Dutta
  • 3,102
  • 19
  • 23
4

Look at this statement

cout << -2[arr];

First, know that even though it looks strange the following is true

2[arr] == arr[2]

That being said operator[] has higher precedence than -. So you are actually trying to invoke

-(arr[2])
Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
3

In C and C++, 2[arr] is actually the same thing as arr[2].

Due to operator precedence, -2[arr] as parsed as -(2[arr]). This means that the entire expression evaluates to negating the 3rd element of arr, i.e. -30.

TartanLlama
  • 59,364
  • 11
  • 141
  • 183