Impossible indexing of C ++ arrays

Possible duplicate:
In C arrays, why is this so? a [5] == 5 [a]
Access to arrays by index [array] in C and C ++

I just found what seems like an error in my code, but not only does it compile, but it also works as expected initially ...

Consider the following snipet code:

#include <string> #include <iostream> using namespace std; class WeirdTest { public: int value; string text; WeirdTest() : value(0), text("") {} virtual ~WeirdTest() {} void doWeirdTest() { value = 5; string name[] = { "Zero", "One", "Two", "Three", "Four", "Five" }; text = value[name]; cout << "text: " << text << endl; } }; int main(int argc, char** argv) { WeirdTest test; test.doWeirdTest(); return 0; } 

Instead of text=value[name]; it should have been text=name[value]; , but the compiler does not complain, and the resulting binary is the same whether there is an β€œerror” or not. I am compiling with g ++ 4.6.3, and if someone knows what is going on here, I would be very grateful. Maybe this is something in the standard that I missed? Is automatic error correction in C ++ 0x possible ?;)

Thank you very much,

Greetings!

+4
source share
1 answer

Yes, this is a curious "feature." In fact, what happens is that the compiler translates a[i] to *(a + i) , so the array index and array address are actually interchangeable.

Note that it is valid only if operator [] not overloaded.

+9
source

Source: https://habr.com/ru/post/1447703/


All Articles