C language learning --union (Commonwealth, union) and Application

C language union (union, union) and Application

In structure (variable), each member of the structure storage order, each member has its own separate memory location. All members of the union (union) variables share the same memory areas / memory. Therefore, each time in a joint variable values ​​can only save one of its members.

Joint variables can be initialized directly in the definition, but this can only initialize the first members. The following example describes a joint variable is defined and initialized.

1 uunion data
2 {
3     char n;
4     float f;
5 };
6 union data u1 = {3}; //只有u1.n被初始化

The main feature of union are:

  1. union members can define multiple, union maximum size determined by the size of the members;

  2. union members share the same memory size, you can only use one of them members;

  3. A member of a union assignment, will cover the value of the other members (but the premise is the same number of bytes occupied by members, when members of the Number of Bytes not only cover while the corresponding byte value, such as members of char on assignment members will not overwrite the entire int, char because only one byte, and int total of four bytes);

  4. store the order amount is that all union members from a low start address stored.
    Thus, with the combination (Union) to determine the size of the end of the CPU (Indian order):

 1 int checkCPU()
 2 {
 3     union w
 4     {
 5         int a;
 6         char b;
 7     }c;
 8     
 9     c.a = 1;
10     
11     return ( c.b == 1 );
12 }

Guess you like

Origin blog.csdn.net/tonglin12138/article/details/93754079