Unions in C Language:
Unions in C
Unions in C are user-defined data types similar to structures. However, in unions, all members share the same memory location, meaning a union can store different data types in the same memory location, but only one at a time.
Declaring and Using Unions
#include
// Define a union
union Data {
int i;
float f;
char str[20];
};
int main() {
// Declare a union variable
union Data data;
// Access and print union members
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %.1f\n", data.f);
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);
return 0;
}
Accessing Union Members Using Pointers
You can access union members using pointers to unions. The arrow operator (->
) is used to access members through a pointer.
#include
#include
// Define a union
union Data {
int i;
float f;
char str[20];
};
int main() {
// Declare a union variable
union Data data;
// Declare a pointer to the union
union Data *ptr;
// Assign the address of data to the pointer
ptr = &data;
// Access and print union members using the pointer
ptr->i = 10;
printf("ptr->i: %d\n", ptr->i);
ptr->f = 220.5;
printf("ptr->f: %.1f\n", ptr->f);
strcpy(ptr->str, "C Programming");
printf("ptr->str: %s\n", ptr->str);
return 0;
}
Differences Between Unions and Structures
Unions and structures are similar but have key differences:
- In a structure, each member has its own memory location. In a union, all members share the same memory location.
- The size of a structure is the sum of the sizes of all members. The size of a union is the size of the largest member.
- Only one member of a union can be accessed at a time, whereas all members of a structure can be accessed independently.
Example: Union of Different Data Types
#include
#include
// Define a union
union Data {
int i;
float f;
char str[20];
};
int main() {
// Declare a union variable
union Data data;
// Access and print union members
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %.1f\n", data.f);
strcpy(data.str, "C Programming");
printf("data.str: %s\n", data.str);
return 0;
}
Example: Union with Nested Structures
#include
#include
// Define a structure
struct Address {
char city[50];
char state[50];
};
// Define a union with a nested structure
union Person {
int id;
struct Address address;
};
int main() {
// Declare a union variable
union Person person;
// Access and print union members
person.id = 101;
printf("person.id: %d\n", person.id);
strcpy(person.address.city, "New York");
strcpy(person.address.state, "NY");
printf("person.address.city: %s\n", person.address.city);
printf("person.address.state: %s\n", person.address.state);
return 0;
}