1

I'm making a 4x4 Matrix class, with the data internally represented as an array of 16 floats. Sometimes I may want to access this array directly, but other times I may just want to access an array slot by name.

class Matrix{
    union{
        float array[16];
        struct{
            float a1, a2, a3, a4;
            float b1, b2, b3, b4;
            float c1, c2, c3, c4;
            float d1, d2, d3, d4;
        }named;
        struct{
            float a[4];
            float b[4];
            float c[4];
            float d[4];
        }row;
    }
}

// use
m.array[3] = 1.5f;
m.named.d1 = m.row.a[3];
printf("%f", m.named.d1); // should be 1.5

Is this type of thing sane, or will it massively backfire in ways I cannot begin to dream of?
It seems like the later, but I really enjoy having multiple access methods.

This is for manipulating 3D points for graphics stuff. It's a separate question in itself, but any suggestions for a library that has these things already figured out is entirely welcome.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
  • 2
    Accessing inactive union member is an [undefined behavior in C++](http://stackoverflow.com/questions/11373203/accessing-inactive-union-member-undefined) (not C). Though it works on some compilers, it can fail on others. So at least you cannot claim that your code is portable. – Ivan Aksamentov - Drop Jul 08 '14 at 05:50
  • @drop - aw, I was afraid of that. I guess I can technically use getter methods, but 16+ method definitions is too much trouble. I guess I'll just have to stick to an array – Anne Quinn Jul 08 '14 at 06:02
  • 1
    If you want to provide a convenience for user, you could also overload `operator[]` or `operator()`, to imitate multidimensional array. That is how most C++ math libraries do it. Some of them also provide different ways of "streaming into and out of" matrix/vector via overloaded `operator<<` and `operator>>` This way you keep you code sane and give user syntactic sugar even better than union aliasing could give – Ivan Aksamentov - Drop Jul 08 '14 at 06:06

0 Answers0