Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impossible C++ array indexing [duplicate]

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
Accessing arrays by index[array] in C and C++

I just found what seems to be a bug in my code, but not only it compiles, it also works as expected initially...

Consider the following code snipet:

#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 having text=value[name]; it should have been text=name[value]; but the compiler does not complain, and the resulting binary code is the exact same whether the "bug" is here or not. I'm compiling using g++ 4.6.3, and if someone know what is going on here I would be very grateful. Could it be something in the standard that I missed ? Automatic bug-fix in C++0x maybe ? ;)

Thanks a lot,

Cheers !

like image 856
Pillard Avatar asked Jan 14 '23 22:01

Pillard


1 Answers

Yes, that's a curious "feature". Actually what happens is that the compiler translates the a[i] into *(a + i), so array index and array address are actually interchangeable.

Note, it's valid only if operator [] isn't overloaded.

like image 51
SomeWittyUsername Avatar answered Jan 24 '23 22:01

SomeWittyUsername