11

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?

1
  • It's called stupid retro-compatibility with K&R C. Commented Dec 14, 2015 at 19:20

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

back in the day, when i learned C by myself, there was rarely a mention that s is sizeof arr[0], good you added it in :)
3

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++.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.