Unions
Understanding unions and how they differ from structures. Using unions to save memory.
Introduction to Unions in C Programming
What are Unions?
This lesson introduces the concept of unions in C programming. It covers the basic syntax and declaration of unions, and highlights their fundamental purpose: allowing different data types to share the same memory location.
In C, a union is a special data type similar to a structure, but with a crucial difference: all its members share the same memory location. This means that at any given time, only one member of the union can hold a value. When you assign a value to one member, all other members effectively lose their previous values.
Why Use Unions?
Unions are used primarily to:
- Conserve Memory: When you know that only one of several possible data types will be used at a time, a union allows you to store them in the same memory space, reducing memory footprint.
- Represent Overlapping Data: Sometimes you need to represent the same data in different ways (e.g., as an integer or as an array of bytes). Unions can be useful in such scenarios.
- Data Type Flexibility: They allow you to store different types of data in the same variable at different times.
Syntax and Declaration
The syntax for declaring a union is similar to that of a structure:
union myUnion {
int integerValue;
float floatValue;
char characterValue;
};
In this example, myUnion
can hold an integer, a float, or a character. The size of myUnion
will be the size of its largest member (in this case, likely the float
).
Accessing Union Members
You access union members using the dot (.
) operator, just like with structures:
union myUnion data;
data.integerValue = 10;
printf("Integer value: %d\n", data.integerValue);
data.floatValue = 3.14;
printf("Float value: %f\n", data.floatValue);
data.characterValue = 'A';
printf("Character value: %c\n", data.characterValue);
// At this point, only characterValue holds the actual assigned value. integerValue and floatValue are overwritten.
Important Note: When you assign a value to one union member, you're overwriting the value of all other members. It's your responsibility to track which member is currently valid. Using a separate variable to indicate the "type" of data currently stored in the union is a common practice.