Int [array pointer] in C ++ standard?

As I found out, you can write the following code:

char *a = new char[50]; for (int i = 0; i < 50; ++i) { i[a] = '5'; } 

It compiles. It works. He does the same thing as

 char *a = new char[50]; for (int i = 0; i < 50; ++i) { a[i] = '5'; } 

This is simply because:

  • a[b] is implemented as the macro *(a + b) by default, and the fact that both code instances are valid is just case / compiler specific
  • it is standardized somewhere, and the result of such algorithms should be the same on each platform

It is reasonable to assume that the addition should be commutative, but if we implement operator[] in this way, we have done something else commutative, which may not be the way we wanted.

An interesting fact is the lack of a pointer[pointer] operator[] , so operator[] not a macro.

I know this badly. I know this confuses people who read the code. But I want to know if this is just an accident, and it will not work in a distant land, where unicorns have seven legs and horns on their left cheek.

+7
c ++ arrays syntax pointers
source share
3 answers

C ++ Standard, ยง 8.3.4, Note 7 (p. 185) (my attention).

Except that it was declared for the class (13.5.5), the index operator [] interpreted in such a way that E1[E2] is identical to *((E1)+(E2)) . Due to the conversion rules that apply to + , if E1 is an array and E2 an integer, then E1[E2] refers to the E2th member of E1 . Therefore, despite its asymmetric appearance, subpitting is a commutative operation .

+10
source share

Here is what the C ++ 11 standard has to say:

Note. Except that it was declared for the class (13.5.5), the index operator [] interpreted in a way that E1[E2] is identical to *((E1)+(E2)) . Due to the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2 -th member of E1 . Therefore, despite its asymmetric appearance, a subscription is a commutative operation. (emphasis added).

So, your assumption that a[b] implemented as *(a + b) is correct, except that it is implemented directly in the compiler, and not as a macro.

+4
source share

The expression E1 [E2] is identical (by definition) to * ((E1) + (E2))

... and then the commutativity of the index and pointer is executed. See your C ++ friendly community standard, section 5.2.1 in this version: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

+1
source share

All Articles