Jump to content
  • Advertisement
Sign in to follow this  
try_catch_this

Using structs and arrays in UNIONS.

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!