// Demonstrates structs and union types in C // Compile: gcc union3.c // Execute: a.out // #include #include int main(){ typedef enum {CASH, CHECK, CREDIT} payments; // Declare a struct, comparable to a record // varData is a union which has 4 names for the same field struct transaction { payments kind; int amount; union // Share space { //int discount; double discount; long checkNumber; char cardNumber[6]; } varData; char expireDate[4]; // Only for kind=CREDIT }; struct transaction myTrans; myTrans.kind = CASH; myTrans.amount = 3; printf("amount is %d\n\n", myTrans.amount); // 3 myTrans.varData.discount = 2.5; printf("discount should be 2.5 and it is %f\n", myTrans.varData.discount); // ??? // Not type safe strcpy(myTrans.expireDate ,"0120"); printf("ExpireDate for a cash: %s\n", myTrans.expireDate); // ??? myTrans.varData.checkNumber = 1234000; printf("checkNumber should be 1234000 and it is %d\n\n", myTrans.varData.checkNumber); // ??? printf("discount should be 2.5 and it is %f\n", myTrans.varData.discount); // ??? printf("discount as an int is %d\n", myTrans.varData.discount); // ??? printf("checkNumber as a float is %f\n", myTrans.varData.checkNumber); // ??? } // amount is 3 // // discount should be 2.5 and it is 2.500000 // checkNumber should be 1234000 and it is 1234000 // // discount should be 2.5 and it is 2.500000 // discount as an int is 1234000 // checkNumber as a float is 2.500000