Possible Duplicate:
C: Where is union practically used?
I know the concept of union but I don't see the actual case in real world coding that I should use union data structure. I will be very appreciated if you guys can give me some examples or tutorials that shows cases using union properly.
Thanks in advance.
Where I use it constantly: parsing a configuration file I store all values in a union data type. E.g. when values can be int types or strings, I would use a data structure as follows:
struct cval_s {
short type;
union {
int ival;
char *cval;
} val;
};
In complexer problems, I use them, too. E.g. once I wrote an interpreter for an easy scripting language, and a value in this language was represented by a struct containing a union.
Imagine having a struct
that keeps a value and the type of that value. When the type is set to a particular type, you would only need to use one of the members of the union
rather than waste space for three of them when you use only one simultaneously.
struct {
int type;
union {
int intval;
double dval;
char cval;
} value;
}
来源:https://stackoverflow.com/questions/6303360/actual-usage-of-union-in-c