Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't arr[-2] equivalent to -2[arr]?

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

Output:

4196160 -30 

Here arr[-2] is out of range and invalid, causing undefined behavior. But -2[arr] evaluates to -30. Why?

Isn't arr[-2] equivalent to -2[arr]?

like image 910
msc Avatar asked Jun 05 '17 09:06

msc


2 Answers

-2[arr] is parsed as -(2[arr]). In C (and in C++, ignoring overloading), the definition of X[Y] is *(X+Y) (see more discussion of this in this question), which means that 2[arr] is equal to arr[2].

like image 169
Chris Jefferson Avatar answered Oct 19 '22 09:10

Chris Jefferson


The compiler parses this expression

-2 

like

unary_minus decimal_integer_literal 

That is definitions of integer literals do not include signs.

In turn the expression

2[arr] 

is parsed by the compiler as a postfix expression.

Postfix expressions have higher precedence than unary expressions. Thus this expression

-2[arr] 

is equivalent to

- ( 2[arr] ) 

So the unary minus is applied to the lvalue returned by the postfix expression 2[arr].

On the other hand if you wrote

int n = -2; 

and then

n[arr] 

then this expression would be equivalent to

arr[-2] 
like image 21
Vlad from Moscow Avatar answered Oct 19 '22 07:10

Vlad from Moscow