[prev] 78 [next]

Unions (cont)

Common use of union types: "generic" variables

#define IS_INT   1
#define IS_FLOAT 2
#define IS_STR   3

struct generic {
   int   vartype;
   union { int ival; char *sval; float fval; };
} myVar;

// treat myVar as an integer
myVar.vartype = IS_INT;
myVar.ival    = 42;
printf("%d\n", myVar.ival);
// now treat myVar as a float
myVar.vartype = IS_FLOAT;
myVar.fval    = 3.14159;
printf("%0.5f\n", myVar.fval);