Definition:
- A union is a special data type available in C that allows the storage of different data types in the same memory location.
- Unlike unions structures can stores different data types in different locations.
- You can define a union with many members, but only one member can contain a value at any given time.
- Unions provide an efficient way of using the same memory location for multiple-purpose.
Declaration:
union [union tag] {
member definition;
member definition;
...
member definition;
} [declaring one or more union variables];
Giving the union tag is optional it works without tag also.
Example:
union Data {
int i;
float f;
char str[45];
} data;
- Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a single variable(data), i.e., the same memory location, can be used to store multiple types of data.
- You can use any built-in or user-defined data types inside a union based on your requirement.
- The memory occupied by a union will be large enough to hold the largest member of the union.
- For example, in the above example, Data type will occupy 45 bytes of memory space because this is the maximum space that can be occupied by a character string. The following example displays the total memory size occupied by the above union example.
Accessing Union Members
Same as Structures To access any member of a union, we use the member access operator (.), and The member access operator is coded as a period between the union variable name and the union member that we wish to access.
Example:
#include <stdio.h>
#include <string.h>
union Shs{
int i;
float f;
};
int main( ) {
union Shs d;
data.i = 10;
data.f = 220.5;
strcpy( d.str, "C Programming");
printf( "d.i : %d\n", data.i);
printf( "d.f : %f\n", data.f);
printf( "d.str : %s\n", data.str);
return 0;
}
Output:
d.i : 1917853763
d.f : 4122360580327794860452759994368.000000
d.str : C Programming
Explaination:
As the data is stored in the same location the integer data and the float data has been corrupted or overwritten by the string data so that when we call integer and float data we get some corrupted value and we can see the String data is displayed correctly as it was stored at the last in the union.
if the code is like this
data.i = 10;
printf( "d.i : %d\n", data.i);
data.f = 220.5;
printf( "d.f : %f\n", data.f);
strcpy( d.str, "C Programming");
printf( "d.str : %s\n", d.str);
then the output will be:
d.i : 10
d.f : 220.500000
d.str : C Programming
Note: More examples will be covered in Problems on the C page
Similarly, you can also learn the structures, arrays, and pointers concept also here
If you have any doubts or you want us to create some more concepts or if you can't solve any problems please give it in the form of your comments.
If you like the content we had given and understood it well then give your valuable rating for this page and comment on your experience in the comment box .