Clarification on Unions
Members - Reputation: 168
Posted 05 February 2002 - 02:07 PM
Posted 05 February 2002 - 04:37 PM
(1) You want something that can hold a value of more than one type (but just one at a time).
For example, there is a struct in Win32 called a VARIANT that contains a type field that is just some numeric identifier for a type followed by a union containing a long, float, void*, etc. It looks like there are actually about 40 different types that it can contain. If they declared each one individually, that would probably be something like 40 types * about 4 bytes per type = about 160 bytes per instance. With a union, it''s probably more like 8 bytes for the value.
These are typically used in places where this kind of flexible is needed such as variables in a scripting language (java-script for example) or keeping a list of properties (without wanting to know about the specific type when storing, loading ,etc.).
(2) You want to be able to access the same value in different ways.
For example, there is a struct in Windows Sockets called an in_addr that represents an IP address. These are 32-bit values that are typically displayed in a more human-friendly format as four groups of 8-bit values (127.0.0.1).
I''ve personally used unions for both reasons. Once I wanted to load in a list of properties from a saved file so I used a union as described in use 1. Another time, I needed to expand a member of struct from one to an array of four but I couldn''t do so in a way that broke existing code. My solution was to create a union that contained the original declaration along with the array -- the original name now referred to the 0th element of the array. Best of both worlds!
Members - Reputation: 134
Posted 07 February 2002 - 06:45 PM
this is useful for copying the stringdata, since its 4 times faster to copy as int than as a char...
unions are basically around so that we dotn gotta do lots of ugly casting... which we tend to like to do, when people arent screaming "unions, bastard!!" at us.
Edited by - evilcrap on February 8, 2002 1:47:28 AM
Posted 12 February 2002 - 05:46 PM
Think of it this way. A garage.
You tell the designer that you want a garage that will hold either a sports car or a SUV.
The designer makes it is just large enough to hold the SUV, but the sports car will fit.
Note that you can only store 1 car there at at time.
The union command allocates enough memory on the heap for the largest size variable. HOW you use that memory is up to you, but you cannot magically store lots of stuff there, only 1.