The union is a data format capable of storing various types of data, but only while the memory wherein one type.
. 1 Union one4all 2 { . 3 int int_val; . 4 Double double_val; . 5 Long long_val; . 6 }; . 7 . 8 one4all Pail; . 9 pail.int_val = . 4 ; // Pail storage type int. 4 10 pail.double_val = 4.9 ; // Pail this when storing double type 4.9, 4 before it was abandoned
Each union can store a value, it must have enough space to store the largest member, so that the common length of the body length is typically the largest member.
Use: When two or more items of data formats (but will not be used at the same time), save space.
Anonymous union anonymous union
1 union widget 2 { 3 char brand[10]; 4 int type; 5 union 6 { 7 long id_num; 8 char id_char[20]; 9 }; 10 }; 11 12 widget prize; 13 if (prize.type == 1) 14 cin >> prize.id_num; 15 else 16 cin >>prize.id_char;