• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
freeworld

What are unions good for?

28 posts in this topic

Bored and reading in my favourite room ;) I noticed out of all the c/c++ books I have only one even spends a paragraph talking about unions, and from the little reading here I understand what unions are and what they do... but other than for defining color values that can acces individual channels or the whole color I can't think what they would be good for.

What would you use a union for? Is it just depricated idea? even with the color idea, a class/struct could easily do the same thing and probably better.
0

Share this post


Link to post
Share on other sites
[quote name='Antheus' timestamp='1298676237' post='4779163']
They allow different interpretation of same memory location.
[/quote]

I know what they do, I was more interested in how they would be used in the real world and why? Just trying to further my knowledge.
0

Share this post


Link to post
Share on other sites
Some form of event maybe with an "additional info" variable.

additionalInfo.Int = 10;
additionalInfo.Float = 10.0f

Obviously you can just cast but I believe you can also have type that take a larger number of bytes (such as a double) but use only a bit of it (unsigned int).

additionalIfno.Double = 1.0;
additionalInfo.UnsignedInt = 10;

double takes up more memory than an unsigned int
0

Share this post


Link to post
Share on other sites
[quote name='Nanoha' timestamp='1298678335' post='4779171']
Some form of event maybe with an "additional info" variable.

additionalInfo.Int = 10;
additionalInfo.Float = 10.0f

Obviously you can just cast but I believe you can also have type that take a larger number of bytes (such as a double) but use only a bit of it (unsigned int).

additionalIfno.Double = 1.0;
additionalInfo.UnsignedInt = 10;

double takes up more memory than an unsigned int
[/quote]

I believe that is incorrect... the union should take up the space of the largest variable?
0

Share this post


Link to post
Share on other sites
[quote]I was told that the standard only supports accessing the element in a union which was last written to, in which case it's only safe to use unions to save space. [/quote]
I believe you have point there. Personally I haven't seen any compiler that does not exhibit the behaviour I posted earlier. I dare say, if the bit-field size of each union member is identical, and that their mapping is guaranteed to be at the same physical memory location, then you can expect this behaviour to be consistent. Unless of course there is some kind of data conversion behind the scenes when it's written to memory. I've seen unions used as a crude reinterpret_cast mechanism in C; not exactly 100% safe, but generally they were not a problem if some precautions were taken.
0

Share this post


Link to post
Share on other sites
Unions can also help avoid aliasing problems when accessing both different bytes of a multibyte type and the type itself (source: http://locklessinc.com/articles/mutex_cv_futex/ )
0

Share this post


Link to post
Share on other sites
[quote name='taz0010' timestamp='1298697104' post='4779223']
Isn't using unions in this way undefined behaviour according to the standard? I was told that the standard only supports accessing the element in a union which was last written to, in which case it's only safe to use unions to save space. Combine this with the rules on strict aliasing, and pretty much any form of type pruning relies on compiler specific behaviour.

Are there specific compilers where using unions for type pruning does not work though?


[/quote]

Yes that and most of what has been posted here is undefined behaviour according to the standard. You really should have an identifier which signals which element is currently stored in the union, then only read this element and none of the others.
0

Share this post


Link to post
Share on other sites
Unions are also pretty useful in pooling-- assuming your pooled objects are big enough, you can temporarily reinterpret them as being, say, a node in a doubly-linked list. This also has the added benefit of being standards-compliant!
0

Share this post


Link to post
Share on other sites
You use unions to save memory. Think of a RPG. An item can be a potion, a weapon, an armor, a quest item, a scroll, a permanent stat up, etc. So an item needs to provide a member for health healing, mana healing, and buffing or debuffing in case it is a potion, attack power, chance to hit, and critical hit chance in case it's a weapon, armor class, magic resistance and evasion in case it's armor, spell to use for scrolls, etc. So that's a lot of variables even though you only ever use two or three at a time. This is a very good place to use a union, where the specific variables are stored into a union of structs, each containing the variables of a particular class of item.

Of course, using unions and data structs is an older style of programming. Polymorphism and real-time type information are a much more powerful way to make similar items with different content. However, in the example above, inventory is something you probably want serialized, and serializing polymorphic objects isn't always simple, whereas a simple byte-by-byte copy operation will do the trick for unions and data structures, so it's not to say there's no advantage to unions versus polymorphism.
0

Share this post


Link to post
Share on other sites
Others may have shown the most common using of union.

Here is a less common but also very useful trick:

[code]
union WithOrWithoutName {
TypeA * pa;
TypeB * pb;
};
[/code]

Then you can use a same pointer in both type of TypeA and TypeB, no needing any type cast.
Qt used this trick in some container classed, I also used it in my code.
1

Share this post


Link to post
Share on other sites
I had a proper read though the C99 standards the other day and I have to concede, it's probably best to abandon the examples I posted earlier. It's real shame though, suddenly unions have become less useful in my mind.
0

Share this post


Link to post
Share on other sites
A common use is to lay out a friendlier structure over the top of a larger type which facilitates, for example, SIMD operations, a'la:

[code]
struct Vec4{
union {
__m128 v;
struct { float x, y, z, w; };
};
};
[/code]
0

Share this post


Link to post
Share on other sites
[quote name='Ravyne' timestamp='1298835448' post='4779779']
A common use is to lay out a friendlier structure over the top of a larger type which facilitates, for example, SIMD operations, a'la:

[code]
struct Vec4{
union {
__m128 v;
struct { float x, y, z, w; };
};
};
[/code]
[/quote]


Can people stop posting this crap as if it is defined, or at least state that it is platform specific. Ravyne has taken this to another level filled with even more undefined/illegal goodness, requiring language extensions.
Maybe this is should be in the FAQ.
2

Share this post


Link to post
Share on other sites
Fair enough that I didn't take great pains to enumerate potential downsides, but to be fair I gave that code no endorsement either -- I simply put it forward as one (rather common) example of its use. I didn't even pull that from my own code, but did a quick Google search and pulled it from the first hit, which happened to be a thread here on gamedev. I could have taken the time to vet the code, but I was in a rush.

In any event, if you have an issue with the code itself, lets pick it apart and demonstrate what's wrong with this (again, common -- even if platform specific) practice, rather than leveling near-accusations that I've undertaken this enterprise as some sort of malice or ignorance-driven desire to mislead.
0

Share this post


Link to post
Share on other sites
A union like that between a struct and a native SIMD type can be hard to avoid in performance-critical code (such as a vector/matrix math library on a console) even though it's platform- and even compiler-specific. On the other hand, you're probably better off writing accessor functions using SIMD intrinsics since you can avoid writing a SIMD register to memory and reading a component back into a floating-point register.

Union are dangerous power tools that should be used only when necessary and when you know what you're getting yourself into. Most of the time, there are cleaner or safer ways to attack the problem. :)
0

Share this post


Link to post
Share on other sites
[quote name='Ravyne' timestamp='1298871965' post='4779971']
Fair enough that I didn't take great pains to enumerate potential downsides, but to be fair I gave that code no endorsement either -- I simply put it forward as one (rather common) example of its use. I didn't even pull that from my own code, but did a quick Google search and pulled it from the first hit, which happened to be a thread here on gamedev. I could have taken the time to vet the code, but I was in a rush.

In any event, if you have an issue with the code itself, lets pick it apart and demonstrate what's wrong with this (again, common -- even if platform specific) practice, rather than leveling near-accusations that I've undertaken this enterprise as some sort of malice or ignorance-driven desire to mislead.
[/quote]
I think the problem was that there were a number of threads in previous posts that did this already. You appeared to be adding to the "noise" of bad practise perhaps without having read the existing posts. The only thing missing is a chapter/verse in the standard, but presumably if one has a copy, it's easy enough to look it up.
0

Share this post


Link to post
Share on other sites
[quote name='Jan Wassenberg' timestamp='1298735697' post='4779344']
Is that the way you drive, or want an airline to operate - "not exactly 100% safe, but generally [..] not a problem"?[/quote]
Yes, that is how such industries operate.

Each aircraft launches with hundreds of "issues". They do a cost analysis. How much to fix and replace vs. cost of death. A person is valued at around $2 mil IIRC. Cost of most replacements can quickly go above a plane's worth of people. Same for medical gear, nuclear facilities, chemicals, ...

Just saying...
0

Share this post


Link to post
Share on other sites
I've seen code that uses unions for a generic message type to pass around to multiple area. For example, if you have an Audio and Video subsystem, and a generic message type, you could do something like this (in C):

[code]

typedef enum
{
VIDEO_SUBSYSTEM=0,
AUDIO_SUBSYSTEM,
MANAGER_SUBSYSTEM,
MAX_SUBSYSTEMS
} etMsgLocation;

typedef struct
{
etAudioType eAudioType;
uint16 SampleRate;
uint16 Channels;
uint32 BufferSize;
uint8 *pBuffer;
} AudioMsg;

typedef struct
{
etVideoFormat eVideoFormat;
union
{
tMpeg4CompressData Mp4Data;
tAviCompressData AviData;
tMpeg2CompressData Mp2Data;
} o;
} tVideoMsg;

typedef struct
{
etMsgLocation eMsgDestination;
etMsgLocation eMsgSource;
union
{
tAudioMsg AudioMsg;
tVideoMsg VideoMsg;
} o;
} tSystemMsg;

tSystemError SendSystemMessage(tSystemMsg *pSystemMsg);

[/code]

This code compresses audio and video specific informaiton into one structure, but shares the memory location.

Also, the Video Msg type shares memory locations with the different possible compression types.

So, this is one way I commonly see unions used.
0

Share this post


Link to post
Share on other sites
[quote]You mean "type punning", for which there are actually two standard and perfectly safe methods - serializing through char*, which has a special dispensation concerning aliasing, or memcpy.[/quote]

I understand that you can cast a type to char*, but it's not compliant to cast char* back into another type.
Suppose I want to bitshift a floating point value. (This is part of a neat little hack used in some 3D engines to approximate the square root operation) I'd have to do something like this right?


float num = 5416.53;
int dest;
char* cNum = reinterpret_cast<char*>(&num);
char* cDest = reinterpret_cast<char*>(&dest);
std::copy(cNum,cNum+sizeof(dest),cDest);
dest >>= 1;
std::copy(cDest,cDest+sizeof(cNum),cNum);


Clearly this is impractical if the reason for using type punning is performance. Seems far more practical to settle for the non-compliant method of using unions. At least it avoids violating strict aliasing rules which are actually enforced on certain major compilers.

Speaking of strict aliasing, how does one use the malloc function when it returns a void pointer? Isn't casting this pointer to another type considered a violation? Or is converting void* to anything else another exception along with cast to char?

0

Share this post


Link to post
Share on other sites
[quote]I understand that you can cast a type to char*, but it's not compliant to cast char* back into another type.[/quote]
And what is this understanding based on?
You can cast until the cows come home. What is important is that all accesses to a stored value occur through the same pointer (or "by an lvalue expression that has .. character type" [ANSI C99 6.5#7]).

[quote](This is part of a neat little hack used in some 3D engines to approximate the square root operation)[/quote]
Which used to be a good idea 10..15 years ago, but I'd expect it to be slower now than the SQRTSS instruction generated by a simple call to fsqrtf().

[quote]I'd have to do something like this right?[/quote]
Ooh. Numerous problems with that code:
- unnecessary reinterpret_cast
- incorrect end pointer in the second std::copy
- using std::copy, which must be able to handle overlapping ranges, instead of memcpy
- right-shifts on negative integers are undefined

[quote]Clearly this is impractical if the reason for using type punning is performance.[/quote]
That is anything but clear. Can you justify that statement?
After fixing the above, I see the following code generated (ICC 12.1):
000000013F7B1058 mov edx,dword ptr [dest]
000000013F7B105B shr edx,1
000000013F7B105D mov dword ptr [dest],edx

[quote]Speaking of strict aliasing, how does one use the malloc function when it returns a void pointer? Isn't casting this pointer to another type considered a violation?[/quote]
Nope. Please see ANSI C99 6.7.3#15.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0