Книга: 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;

Оглавление книги


Генерация: 1.713. Запросов К БД/Cache: 3 / 1
поделиться
Вверх Вниз