C Unions
A union in C is a user-defined data type that allows you to store different data types in the same memory location. Unlike structures, where each member has its own memory, a union allocates one shared memory block that is large enough to hold its largest member. This means that at any given time, only one member can hold a meaningful value.
Why Use Unions?
Unions are mainly used to save memory when you need to store one of several possible data types, but not all at once. This is especially useful in embedded systems or memory-constrained environments. With unions, you can design data structures that efficiently handle different types of data without wasting memory.
Properties of Unions in C
Unions in C have unique characteristics that distinguish them from structures. Below are some key properties of unions:
- Shared Memory: All members of a union share the same memory location. This means that at any given time, only one member can hold a valid value.
- Memory Efficiency: The size of a union is determined by the size of its largest member, which helps in conserving memory when different data types are not needed simultaneously.
- Mutually Exclusive Data: Since all members share the same memory, writing to one member will overwrite the values of the other members. This makes unions ideal for storing one of several possible data types.
- Declaration Syntax: Unions are declared using the
union
keyword. Their syntax is similar to structures, but their behavior in memory allocation is different. - Anonymous Unions: Unions can be declared without a name (anonymous unions) inside structures, allowing direct access to their members without using a union name.
- Type Management: Unions do not provide built-in type safety. It is the programmer’s responsibility to track which member is currently storing a valid value.
- Use Cases: Unions are particularly useful in memory-constrained environments (such as embedded systems) and in scenarios where a variable may take on multiple forms but only one form is used at a time.
Understanding these properties is essential when designing data structures that require memory efficiency and flexibility in handling different data types.
Key Differences Between Structures and Unions
Here are the main differences between a structure and a union in C:
- Memory Allocation: A structure allocates separate memory for each member, while a union allocates one memory block equal to the size of its largest member.
- Data Storage: In a structure, all members can hold values at the same time. In a union, updating one member overwrites the others.
Syntax for Declaring a Union
The syntax for declaring a union is very similar to that for declaring a structure, except that you use the keyword union
instead of struct
.
union union_name {
datatype member1;
datatype member2;
// additional members...
};
Note: The size of the union is determined by its largest member because it must reserve enough memory to store that member.
Example 1: Basic Union vs. Structure
This example demonstrates the difference between a structure and a union. We define a structure test1
with two integer members and a union test
with two integer members. Notice how assigning a value to one member of the union affects the other.
C Program
#include <stdio.h>
struct test1 {
int x, y;
};
union test {
int x, y;
};
int main() {
// Structure: both members have their own memory
struct test1 t1 = {1, 2};
// Union: both members share the same memory
union test t;
t.x = 3; // t.y also becomes 3 because they share the same memory
printf("After assigning x in union: %d %d\n", t.x, t.y);
t.y = 4; // Now t.x becomes 4 as well
printf("After assigning y in union: %d %d\n", t.x, t.y);
printf("Structure values: %d %d\n", t1.x, t1.y);
return 0;
}
Explanation:
struct test1
defines a structure with two integersx
andy
, each stored in separate memory locations.union test
defines a union with two integers, but both share the same memory location.- When
t.x
is set to 3,t.y
also appears as 3 because they occupy the same space. - Changing
t.y
to 4 updates the shared memory, sot.x
now becomes 4. - The structure
t1
retains its independent values (1 and 2) since its members are stored separately.
Output:
After assigning x in union: 3 3
After assigning y in union: 4 4
Structure values: 1 2
Example 2: Using a Union Inside a Structure
In this example, we embed an anonymous union within a structure. The union is used to store mutually exclusive data (either a name or a roll number), and an additional field stores the student’s marks. This design helps save memory by using the union to hold one of two values at a time.
C Program
#include <stdio.h>
struct student {
union { // Anonymous union: no name is required
char name[10];
int roll;
};
int mark;
};
int main() {
struct student stud;
char choice;
printf("\nEnter 'y' if you want to input name, or 'n' for roll number: ");
scanf(" %c", &choice); // Notice the space before %c to consume any leftover whitespace
if (choice == 'y' || choice == 'Y') {
printf("Enter name: ");
scanf("%s", stud.name);
printf("Name: %s\n", stud.name);
} else {
printf("Enter roll number: ");
scanf("%d", &stud.roll);
printf("Roll: %d\n", stud.roll);
}
printf("Enter marks: ");
scanf("%d", &stud.mark);
printf("Marks: %d\n", stud.mark);
return 0;
}
Explanation:
- The
struct student
contains an anonymous union that can store either aname
(character array) or aroll
(integer), along with an integermark
. - The program asks the user whether to enter a name or a roll number, then reads the appropriate input.
- The union ensures that only one of
name
orroll
is stored at any given time, thus saving memory. - Finally, the student’s marks are read and printed along with the chosen identifier.
Sample Output:
Enter 'y' if you want to input name, or 'n' for roll number: y
Enter name: john
Name: john
Enter marks: 45
Marks: 45
Example 3: Structures Inside a Union
This example shows how to define a structure inside a union. Here, the union contains a structure that holds multiple pieces of information about a student. This approach is useful when you want to group related data together and allow different interpretations of the same memory space.
C Program
#include <stdio.h>
int main() {
// Define a structure to store student details
struct student {
char name[30];
int rollno;
float percentage;
};
// Define a union that contains the student structure
union details {
struct student s1;
};
union details set;
printf("Enter student details:\n");
printf("Enter name: ");
scanf("%s", set.s1.name);
printf("Enter roll number: ");
scanf("%d", &set.s1.rollno);
printf("Enter percentage: ");
scanf("%f", &set.s1.percentage);
printf("\nThe student details are:\n");
printf("Name: %s\n", set.s1.name);
printf("Roll Number: %d\n", set.s1.rollno);
printf("Percentage: %.2f\n", set.s1.percentage);
return 0;
}
Explanation:
- A structure
student
is defined with fields for the name, roll number, and percentage. - A union
details
is declared that contains thestudent
structure as its member. - The program reads the student’s details into the union’s structure and then prints them.
- This example illustrates how unions can encapsulate complex data structures, although only one interpretation (in this case, the student record) is used at a time.
Sample Output:
Enter student details:
Enter name: alice
Enter roll number: 101
Enter percentage: 88.5
The student details are:
Name: alice
Roll Number: 101
Percentage: 88.50
Conclusion
In this tutorial, we explored C unions and learned that:
- A union allows different data types to share the same memory, saving space.
- Only one member of a union can store a valid value at a time.
- Unions are useful in memory-constrained systems and when data fields are mutually exclusive.
- We compared unions with structures, discussed their syntax, and saw multiple practical examples.