// Demonstrates structs and union types in C
// Compile: gcc union3.c
// Execute: a.out
//
#include <stdio.h>
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
{
//int discount;
double discount;
long checkNumber;
char cardNumber[6];
// char expireDate[6];
} varData;
};
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
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); // ???
}