Joint
The difference between union and structure is that the structure applies a memory space for each field, and the union just applies a memory space and all the fields are saved in this space, the size of the space is determined by the longest in the field, and we begin to define a union
1 // Definition of Union 2 typedef union{3 Short count; 4 float weight; 5 float volume; 6 } quantity;
Combined use we can assign values in a number of ways
1typedefstruct{2 Const Char*color;3 quantity amount;4 }bike;5 6 intMain () {7 //to represent the number of bicycles with a union8Bike b={"Red",5};9printf"Bike color:%s count:%i\n", b.color,b.amount.count);Ten //use a joint to represent the weight of a bicycle OneBike b2={"Red",. amount.weight=10.5}; Aprintf"Bike color:%s count:%f\n", b2.color,b2.amount.weight); - return 0; -}
But it can be very easy to get into trouble when reading the values of the Union, for example, we saved a float type field, but it was read from the short field and got a value that was irrelevant to the expectation.
Enumeration
To avoid confusing the data types of fields like union, we can use enumerations
1#include <stdio.h>2 3 //definitions and struct classes for enumerations4typedefenumcolors{red,black,blue,green} colors;5 6 intMain () {7Colors favorite=BLUE;8printf"%i", favorite);9 return 0;Ten}
If you want to save more than one data type L union The enumeration is more appropriate, then to save multiple data, enumeration is more suitable than union
C Language Learning 015: Union (Union) and enumeration (enum)