Is there an automatic way to keep track of which field of a union is in use?
C Interview Questions and Answers
(Continued from previous question...)
Is there an automatic way to keep track of which field of a union is in use?
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.)
(Continued on next question...)
Other Interview Questions
|