C语言学习: 联合体
1 #include <io_utils.h> 2 3 #define OP_PRINT_INT 0 4 #define OP_PRINT_DOUBLE 1 5 #define OP_PRINT_STRING 2 6 7 typedef union Operand { 8 int int_operand; // 4 9 double double_operand; // 8 10 char *string_operand; // 8 11 } Operand; 12 13 typedef struct Instruction { 14 int operator; 15 Operand operand; 16 } Instruction; 17 18 void Process(Instruction *instruction) { 19 switch (instruction->operator) { 20 case OP_PRINT_INT: PRINT_INT(instruction->operand.int_operand); 21 break; 22 case OP_PRINT_DOUBLE: PRINT_DOUBLE(instruction->operand.double_operand); 23 break; 24 case OP_PRINT_STRING: puts(instruction->operand.string_operand); 25 break; 26 default: 27 fprintf(stderr, "Unsupported operator: %d\n", instruction->operator); 28 } 29 } 30 31 int main() { 32 PRINT_INT(sizeof(Operand)); 33 34 Operand operand; // = {.int_operand=5, .double_operand=2.0}; 35 operand.int_operand = 5; 36 operand.double_operand = 2.0; 37 PRINT_INT(operand.int_operand); 38 PRINT_DOUBLE(operand.double_operand); 39 40 Instruction instruction = { 41 .operator = OP_PRINT_STRING, 42 .operand = { 43 .string_operand = "Hello World!" 44 } 45 }; 46 47 Process(&instruction); 48 return 0; 49 }