C Language Reference for Script Programmers - Unions



 Unions are very similar to structures. They are defined exactly the same way, substituting the keyword union for struct. The difference between the two is that only one member of a union can be used at a time. If you store a value in one member then all other members are to be considered corrupt. The reason for this is that they all share the same memory. Only enough memory is allocated to hold the largest member of the union. If a value is stored in a member that is smaller than the largest one only a portion of that memory is used. Unions help to conserve memory when you are positive that the members of the struct are mutually exclusive.

Take for example information that might be related to different item types inside of messiah. For example, only a bone needs information on the bones length, falloff etc. At the same time only a mesh item needs to know the filename of the object it represents. Both pieces are mutually exclusive. So there could be an element in the item struct definition that includes a union for all of the different types of data related to different objects.


Let’s say we have an item structure as follows:

typedef struct item_St

char *               ItemName;
motion               Motion;
union mod_data_St    ModuleData;


I’ve only included a few members, the rest are assumed.  The only one we’re really concerned with at the minute is union mod_data ModuleData_St. Here’s how that’s defined:

typedef union mod_data_St

struct bone_data_St bond_data;
struct mesh_data_St mesh_data;


Again I’ve left members out since we’re only concerned with the two listed.

Notice that I’ve used: struct bone_data_St instead of: bone_data. The reason is that those structures are still to be defined. By using the struct keyword and the struct tag that I intend to use in the definition of these structures, I can include in this union definition what is yet to be defined.

Finally I have the definition of the structs for bone_data and mesh_data:

typedef struct bone_data_St

float      falloff;
float      length;


typedef struct mesh_data_St

char *     filename;


Alright, now that I’ve got all of that stuff defined I can actually use it. Let’s say I’ve got a variable of type item:


Now if I determine that the type of this item is going to be a bone I can start filling in the values of the bone_data struct like so:

item.ModuleData.bone_data.falloff = 8.0;
item.ModuleData.bone_data.length = 1.0;

However if this happens to be a mesh item I could do something like:

item.ModuleData.mesh_data.filename = NewFileName;

assuming that NewFileName is a char *.

Remember that both mesh_data and bone_data share the same memory. So writing to one of the structures corrupts the other, which in the previous example is perfectly acceptable since they are mutually exclusive.

Converted from CHM to HTML with chm2web Pro 2.82 (unicode)