Index
Union
A union is a user-defined data type that allows you to store different types of data in the same memory location. Unlike structures, where each member has its own memory location, all members of a union share the same memory location. This means that the size of a union is determined by the size of its largest member.
Here’s the basic syntax for declaring a union:
union union_name {
member1_type member1_name;
member2_type member2_name;
// add more members as needed
};
union_name
: This is the name of the union data type.member1_type
,member2_type
, …: These are the data types of the members of the union.member1_name
,member2_name
, …: These are the names of the members of the union.
You can access the members of a union using the dot (.
) operator, just like you would with a structure.
Here’s an example of how to declare and use a union:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 3.14;
printf("data.f: %f\n", data.f);
strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str);
return 0;
}
Output:
data.i: 10
data.f: 3.140000
data.str: Hello
In this example, we define a union named Data
with three members: i
(integer), f
(float), and str
(character array). We then declare a variable data
of type Data
and demonstrate how to access and modify its members. Note that modifying one member of the union can affect the values of other members, as they all share the same memory location.
Difference Between struct
and union
:
- Structure: Each member of a
struct
has its own memory, and all members can hold values simultaneously. - Union: All members of a
union
share the same memory space, so only one member can hold a value at any given time.