Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ reversing indexer and name of array [duplicate]

Tags:

c++

I came across this online and was wondering if someone might be able to explain this or at least give me a name of what it might be so that I can at least know what I'm googling for.

int main()
{
   int myarray[4] = {0, 100, 200, 300};
   2[myarray] = -999;  //why does this work? what is this called?

   for ( int i = 0; i < 4; i++) 
      cout << myarray[i] << endl;
}

The output is 0, 100, -999, 300

I've ran it. I know it works but why? What is this called?

like image 543
jharr100 Avatar asked Dec 14 '15 19:12

jharr100


2 Answers

The reason this is the case is because arr[n] == *(arr + n).

However, because addition is commutative, *(arr + n) == *(n + arr). Thus, *(n + arr) == n[arr] == *(arr + n) == arr[n].

It might be worth mentioning that *(arr + n) is still a little misleading. In assembly it actually means *(arr + (n * s)) where s is sizeof arr[0], but this is under the covers so you don't need to worry about it.

like image 182
erip Avatar answered Nov 01 '22 08:11

erip


I don't think this particular [ab-]use of the rules for pointer arithmetic has any particular name. It is simply falling out of the way pointer arithmetic is defined in C and C++. Neither of the two language standards makes any special attempt to prevent the reversal of the subscript and the pointer. For example, the relevant C++ rule is in 5.2.1 [expr.sub] paragraph 1:

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type. The result is of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ], except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.

It may work to look for "C++ 5.2.1" or "C++ [expr.sub]" but the use of the reversal isn't that large beyond confusing people who haven't look long enough at C or C++.

like image 38
Dietmar Kühl Avatar answered Nov 01 '22 07:11

Dietmar Kühl