Recently I am working on windows and I found that lot of data structures are defined as struct
with union
as member variables. Example of this would be
When a struct
contains union
members it's generally done as a space saving mechanism. If the struct
can be of certain sub-types by which only certain members are valid then a union
is a good way to not waste space.
For example
enum NumberKind {
Integer,
FloatingPoint
};
struct Number {
NumberKind kind;
union {
int integerValue;
float floatValue;
};
};
In this scenario I've defined a struct
Number which can have type types of numeric values: floating point and integer. It's not valid to have both at the same time so rather than waste space by having both members always defined I created a union
which makes the storage of both equal to the size of the biggest.
Sample Usage of Above as requested
void PrintNumber(Number value) {
if (value.kind == Integer) {
printf("%d\n", value.integerValue);
} else {
printf("%f\n", value.floatValue);
}
}