| FAQ | Newsboard | Telnet | Email TA | Lectures | Assignments | Man pages | Help |
|---|
We have to create a struct that can store either integers or doubles. We could implement this requirement by defining a structure that stored both integers and doubles:
typedef struct {
int type;
int ival;
double dval;
} ELEMENT;
When dealing with integers we are wasting the space taken up by the dval field, and when dealing with doubles we are wasting the ival field. C++ allows us to be more efficient by defining a union structure that allows us to access a piece of memory in one of many ways.
For example:
union NumberType {
int ival;
double dval;
};
By definition a union is a struct that holds only one of
its members at a time. Memory space is allocated according to the
size of the largest member. Thus in the example above, enough memory
would be allocated to hold a double, since doubles require
more space than ints. Here is another example:
union SampleType {
char strMemb[10];
int intMemb;
float floatMemb;
};
SampleType sampleVal;
When sampleVal is created memory is not allocated for
all three members -- Instead memory is allocated according to the size
of the largest members which is strMemb requiring 10 bytes.
Here's a kind of struct I would use.
struct Element{
int type;
union {
int ival;
double dval;
} item;
};
Element sample;
sample.type would access the type member. Then
sample.item.ival would access the ival member and
sample.item.dval would access the dval member.
Things are still a little awkward. It would be better if we could just access the ival field without having to go through the named union member item. C++ allows us to do this by providing anonymous unions.
Our struct then becomes
struct Element{
int type;
union {
int ival;
double dval;
};
};
Element sample;
Now we can access the ival field simply, by using
sample.ival and the dval field by using
sample.dval.
To put things a bit more formally. An anonymous union is a union that is unnamed and does not declare any instances after the right brace. With anonymous unions names are not local to the union. Consider
union {
int someInt;
float someFloat;
};
The scope of someInt and someFloat is the
immediately surrounding scope. In fact someInt and
someFloat are treated as if they were declared outside the
union and dot notation is not used in accessing someInt and
someFloat. Thus
someInt = 56;is a perfectly valid assignment statement.
struct Element{
int type;
union {
int ival;
double dval;
};
};
Element data[50];
declares an array of 50 Elements each of which holds either
an integer value or a double value.