Is it legal to index into a struct?

后端 未结 10 1820
悲哀的现实
悲哀的现实 2020-11-30 01:12

Regardless of how \'bad\' the code is, and assuming that alignment etc are not an issue on the compiler/platform, is this undefined or broken behavior?

If I have a s

10条回答
  •  猫巷女王i
    2020-11-30 02:05

    In C++ if you really need it - create operator[]:

    struct data
    {
        int a, b, c;
        int &operator[]( size_t idx ) {
            switch( idx ) {
                case 0 : return a;
                case 1 : return b;
                case 2 : return c;
                default: throw std::runtime_error( "bad index" );
            }
        }
    };
    
    
    data d;
    d[0] = 123; // assign 123 to data.a
    

    it is not only guaranteed to work but usage is simpler, you do not need to write unreadable expression (&thing.a)[0]

    Note: this answer is given in assumption that you already have a structure with fields, and you need to add access via index. If speed is an issue and you can change the structure this could be more effective:

    struct data 
    {
         int array[3];
         int &a = array[0];
         int &b = array[1];
         int &c = array[2];
    };
    

    This solution would change size of structure so you can use methods as well:

    struct data 
    {
         int array[3];
         int &a() { return array[0]; }
         int &b() { return array[1]; }
         int &c() { return array[2]; }
    };
    

提交回复
热议问题