/** * Program showing the reasonable use of a union * The union is used within a struct that holds * what the union is storing and the union. * **/ #include // These defines cover what could be in the union. // could be done with an enum instead #define INTEGER 1 #define DOUBLE 2 #define CHAR 3 // a type to hold what info the union contains typedef unsigned char unionType; /** * The union, holds an int, double OR char * **/ typedef union { int a; double b; char c; } uuu; /** * A struct to wrap the union and hold its contents * as well as what it contents are * **/ typedef struct { unionType whichOne; uuu foo; } sss; /** * Put an int into the union. * This should be "public" in the struct .c file * @param ii an int * **/ sss putint(int ii) { sss ret; ret.whichOne = INTEGER; ret.foo.a = ii; return ret; } /** * Put a double into the union. * This should be "public" in the struct .c file * @param dd a double * **/ sss putdouble(double dd) { sss ret; ret.whichOne = DOUBLE; ret.foo.b = dd; return ret; } /** * Print the contents of the structure * @param str the structure to be printed * **/ void printStruct(sss str) { switch (str.whichOne) { case INTEGER: printf("INT %d\n", str.foo.a); break; case DOUBLE: printf("DOU %.2f\n", str.foo.b); break; } } int main(int argc, char const *argv[]) { sss aaa[10]; for (int i = 0; i < 10; i++) if (i%2==0) aaa[i] = putdouble(i * 5.0); else aaa[i] = putint(i * 5); for (int i = 0; i < 1000; i++) { printf("%d ", i); printStruct(aaa[i]); } return 0; }