C Language Learning 015: union and enumeration (enum), 015 enum
Union
The difference between the Union and the structure is that the structure will apply for a piece of memory space for each field, while the Union only applies for a piece of memory space and all fields will be saved to this space, the size of this space is determined by the longest field. Next we will start to define a union.
1 // definition of union 2 typedef union {3 short count; 4 float weight; 5 float volume; 6} quantity;
In combination, we can assign values to the Union in many ways.
1 typedef struct {2 const char * color; 3 quantity amount; 4} bike; 5 6 int main () {7 // The number of bicycles in combination is 8 bike B = {"red", 5}; 9 printf ("bike color: % s count: % I \ n ", b. color, B. amount. count); 10 // indicates the weight of a bicycle in combination. 11 bike b2 = {"red ",. amount. weight = 10.5}; 12 printf ("bike color: % s count: % f \ n", b2.color, b2.amount. weight); 13 return 0; 14}
However, when reading the Union value, it is prone to problems. For example, we save a float type field, but read it through the short field to obtain the value that is not relevant to expectation.
Enumeration
To avoid confusion between the data types of fields like Union, we can use enumeration.
1 # include <stdio. h> 2 3 // enumeration definition and structure Class 4 typedef enum colors {RED, BLACK, BLUE, GREEN} colors; 5 6 int main () {7 colors favorite = BLUE; 8 printf ("% I", favorite); 9 return 0; 10}
If you want to save multiple data types, l Union enumeration is more suitable for storing multiple data types.