Using structs and arrays in UNIONS.

Started by
10 comments, last by lucky_monkey 19 years, 2 months ago

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.
Advertisement
I think you'll see that exact union in D3DX's matrix definition... so it should be pretty safe.
what would be the point of doing that?
it seems like 3 ways to do the same thing: hold 16 floats.

Beginner in Game Development?  Read here. And read here.

 

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.
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])
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?
It's just syntactical sugar. There's no real need for it.
It's like how eskimos have 200 different words for snow.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
iMalc: same for operator overloading, a big part of classes, and basically everything in C++ except templates?
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.
Quote:Original post by iMalc
It'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.
Quote:Original post by iMalc
It'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 ;)

This topic is closed to new replies.

Advertisement