Книга: Advanced PIC Microcontroller Projects in C
3.1.17 Unions
3.1.17 Unions
Unions are used to overlay variables. A union is similar to a structure and is even defined in a similar manner. Both are based on templates, and the members of both are accessed using the “.” or “->” operators. A union differs from a structure in that all variables in a union occupy the same memory area, that is, they share the same storage. An example of a union declaration is:
union flags {
unsigned char x;
unsigned int y;
} P;
In this example, variables x and y occupy the same memory area, and the size of this union is 2 bytes long, which is the size of the biggest member of the union. When variable y is loaded with a 2-byte value, variable x will have the same value as the low byte of y. In the following example, y is loaded with 16-bit hexadecimal value 0xAEFA, and x is loaded with 0xFA:
P.y = 0xAEFA;
The size of a union is the size (number of bytes) of its largest member. Thus, the statement:
sizeof(P)
returns 2.
This union can also be declared as:
union flags {
unsigned char x;
unsigned int y;
}
union flags P;
- 3.1.1 Comments
- 3.1.2 Beginning and Ending of a Program
- 3.1.3 Terminating Program Statements
- 3.1.4 White Spaces
- 3.1.5 Case Sensitivity
- 3.1.6 Variable Names
- 3.1.7 Variable Types
- 3.1.8 Constants
- 3.1.9 Escape Sequences
- 3.1.10 Static Variables
- 3.1.11 External Variables
- 3.1.12 Volatile Variables
- 3.1.13 Enumerated Variables
- 3.1.14 Arrays
- 3.1.15 Pointers
- 3.1.16 Structures
- 3.1.17 Unions
- 3.1.18 Operators in C
- 3.1.19 Modifying the Flow of Control
- 3.1.20 Mixing mikroC with Assembly Language Statements