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
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
Again I’ve left members out since we’re only concerned with the two listed.
Finally I have the definition of the structs for bone_data and mesh_data:
typedef struct bone_data_St
typedef struct mesh_data_St
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:
However if this happens to be a mesh item I could do something like:
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)|