Union Common Declaration and common one variable definition:
"Union" is a special class. is also a constructed type of data structure. There are several different types of data that can be defined within a "union".
A variable that is described as a type of "union" that agrees to load whatever kind of data defined by the "union", which shares the same memory,
To achieve space-saving purposes (another space-saving type: bit field).
This is a very special place, but also a characteristic of union.
In addition, as with structs, federated default access permissions are public, and they also have member functions.
Shared body(refer to "Common Body" encyclopedia entry) is a special form of variable, using keywordunion to defineThe shared body (some people are also called "union") statements andA common body variable definition is very similar to a struct. The form is:
Union common body Name {data type member name; data type member name; ...} variable name;
A common body means that several variables share a single memory location, saving different data types and variables of varying lengths at different times.
In union, all of the members of the common body share a space.
At the same time, you can only store the value of one of the member variables.
1. You can define multiple members in union. The size of the Union is determined by the size of the largest member.
2. Union members share memory of the same block size, and only one member can be used at a time.
3. Assigning a value to a member overrides the values of other members (because they share a piece of memory.)
But only if the number of bytes is the same as the member. When the number of bytes in a member is not the same time, only the value on the corresponding byte is overwritten.
For example, assigning a value to a char member does not overwrite the entire int member.
Since Char occupies only one byte, and int accounts for four bytes
4. The Union union is stored in the order that all members are stored from the low address.
Proportional to the following code:
Shared body C language//Xin Yang # include <stdio.h> #include <stdlib.h>typedef union{char c;int a;int b;} Demo;int Main () {Demo d;d.c = ' H ';d. A = 10;D.B = 12;printf ("The byte length at the beginning of the variable is:%d\n", sizeof (d)/4);p rintf ("Three values after assignment: \ n"); printf ("%c\t%d\t%d\n", D.C, D.A, d.b); return 0;}
How to use union in C language