• 13
• 18
• 19
• 27
• 10

# Using structs and arrays in UNIONS.

This topic is 4784 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

union
{
struct
{
float _11, _12, _13, _14;
float _21, _22, _23, _24;
float _31, _32, _33, _34;
float _41, _42, _43, _44;
};
float m[4][4];
float m_afEntry[16];
};


I have seen alot of people write code like this and I wonder if it is ok do use a union like this to access array elements multiple ways.

##### Share on other sites
I think you'll see that exact union in D3DX's matrix definition... so it should be pretty safe.

##### Share on other sites
what would be the point of doing that?
it seems like 3 ways to do the same thing: hold 16 floats.

##### Share on other sites
it is, but it allows the programmer to access those 16 floats in the most appropriate way, without any overhead. sure, it could still be done with just an array of floats, but that would cause ugly (and possibly confusing) code.

##### Share on other sites
This is safe, as long as you don't put a class with nondefault constructors or destructor in such an union.

This is because the data can only be constructed or destructed once, but there is a "default" way and a "nondefault" way.

Stupid example:

union error {  class A1 { public: int * x; ~A1( delete x ); } a;  class A2 { public: int * x; ~A2( free(x) ); } b;};

What happens when such an object is destroyed?

##### Share on other sites
It's just syntactical sugar. There's no real need for it.
It's like how eskimos have 200 different words for snow.

##### Share on other sites
iMalc: same for operator overloading, a big part of classes, and basically everything in C++ except templates?

##### Share on other sites
anonymous struct/classess are non-standard compliant, compilers support it as language extension only so its not portable code, for much better, safer and standard compliant alternative to unions look at this thread.

##### Share on other sites
Quote:
 Original post by iMalcIt's just syntactical sugar. There's no real need for it.It's like how eskimos have 200 different words for snow.

That's true but it can make an unreadable algorithm very very readable. It is also very hard to code some algorithms if you only use a flat array.

##### Share on other sites
Quote:
 Original post by iMalcIt's just syntactical sugar. There's no real need for it.It's like how eskimos have 200 different words for snow.

It's called abstraction, it is fundamental ;)