1 2 3 4 5 6 7 8 9

Use of Unions can be quite elaborate, but what is clear is
that once you have stored an item into a union structure it
is impossible to retrieve unless you know what type of
variable was stored (in this case an integer or a float). It
follows therefore that you must also store in the node some
kind of a TAG that interprets uniquely the item in the
"variant" field.


Typically we might do this though the use of some defined
constants:


#define INTEGER -1
#define FLOAT 1
struct node {
// note datanode creation here
int TAG;
union {
int digits;
float number;
} data;
Nodeptr next;// struct node* next;
}
datanode;

int kind = INTEGER;

// or perhaps FLOAT

datanode.TAG = kind;
if (kind == INTEGER)
datanode.data.digits = 19;
else if (kind == FLOAT)
datanode.data.number = 91.3;
else fprintf (stderr, "Illegal tag %d", kind);

February 15 1998

Page 3

TAM C201 notes