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.
c ++ arrays syntax pointers
styrofoam fly
source share