Union in C
In C, a union is a user-defined data type that allows we to store different types of data in the same memory location. This can be useful when we want to use a single variable to store different types of data at different times, but don’t want to use a lot of memory by creating separate variables for each type.
Here’s an example of how we might use a union in C:
union data {
int i;
float f;
char str[20];
};
union data myData;
In this example, we’ve defined a union called “data” that can store an int, a float, or a character array. We’ve also defined a variable called “myData” that is of type “data”.
We can store different types of data in the same union, but only one type of data can be stored at a time. The size of a union is equal to the size of its largest member.
myData.i = 10;
printf("Integer value: %d\n", myData.i);
myData.f = 220.5;
printf("Float value: %f\n", myData.f);
strcpy(myData.str, "Hello, World!");
printf("String value: %s\n", myData.str);
In this example, we can see that we first store an integer value in the union, then a float value, and finally a string value. If we access the value of myData.f
after storing the string, the value will be undefined, because the memory that was previously used to store the float, now holds the string “Hello, World!”.
Another way in which Unions can be useful is when we want to make use of the same memory space for a number of different variables that are mutually exclusive, for example, in a message protocol where we have a single byte that can contain a number or a character, we can use a union to represent it.
In summary, Unions can be useful when we need to store different types of data in the same memory location and when we want to save memory by using a single variable to store different types of data at different times.
Leave a Comment