4

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 !

Community
  • 1
  • 1
Pillard
  • 49
  • 1
  • 7
    It's behavior that's inherited from C. See: http://www.c-faq.com/aryptr/joke.html – jamesdlin Nov 22 '12 at 10:16
  • 2
    See http://stackoverflow.com/questions/8969684/accessing-array-contents-xn-vs-nx/8969755#8969755 or http://stackoverflow.com/questions/5073350/accessing-arrays-by-indexarray-in-c-and-c – hmjd Nov 22 '12 at 10:17

1 Answers1

9

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.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85