The following code
#include<stdio.h>
int main()
{
int arr[] = {10,20,30};
cout << -2[arr];
return 0;
}
prints -30
. How? Why?
The following code
#include<stdio.h>
int main()
{
int arr[] = {10,20,30};
cout << -2[arr];
return 0;
}
prints -30
. How? Why?
In your case,
cout<<-2[arr];
gets translated as
cout<<-(arr[2]);
because,
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.
regarding the explicit ()
s, you can check about the operator precedence here.
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])
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
.