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 !

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for these answers guys ! I've learned something today :)
This "feature" was a standard trick used by entries in the Obfuscated C Contest.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.