Q: Is there an automatic way to keep track of which field of a union is in use?
A: No. You can implement an explicitly ``tagged'' union yourself:
struct taggedunion {
enum {UNKNOWN, INT, LONG, DOUBLE, POINTER} code;
union {
int i;
long l;
double d;
void *p;
} u;
};
You will have to
make
sure that the code field
is always set appropriately
when the union is written to;
the compiler won't do any of this for you automatically.
(C unions are not like
Pascal variant records.)
References:
H&S Sec. 5.7.3 p. 143