A union in C programming is a user defined data type which may hold members of different sizes and type. Union uses a single memory location to hold more than one variables. However, only one of its members can be accessed at a time and all other members will contain garbage values.
The memory required to store a union variable is the memory required for the largest element of the union. We can use pointers to unions and can access members using arrow operator (->).
Table of Contents
- How to Define a Union in C?
- How to Declare a Union in C?
- How to Initialize a Union in C?
- How to Access Members of a Union?
- Working with Array of Union
- What are the Uses on Union Type?
We can use the unions in the following locations.
- Share a single memory location for a variable and use the same location for another variable of different data type.
- Use it if you want to use, for example, a long variable as two short type variables.
- We don’t know what type of data is to be passed to a function, and you pass union which contains all the possible data types.
So, how we can define and declare and initialize a union in a C Program?
How to Define a Union in C?
Union can be defined by the keyword union
followed by list of member variables contained in curly braces.
1 2 3 4 | union Employee{ int age; long salary; }; |
Here we have defined a union with the name union_name and it has two members i.e. age of type int and salary of type long.
How to Declare a Union in C?
We can declare the union in various ways. By taking the above example we can declare the above defined union as.
1 2 3 4 | union Employee{ int age; long salary; } employee; |
So employee will be the variable of type Employee. We can also declare the above union as: Employee employee;
How to Initialize a Union in C?
We can initialize the union in various ways. For example
1 2 3 4 | union Employee{ int age; long salary; } employee={20000}; |
or we can initialize it as
1 2 | employee.age= 30; employee.salary=20000; |
Normally when we declare the union it is allocated the memory that its biggest member can occupy. So here in our example employee will occupy the memory which a long type variable can occupy.
Similarly union values can be accessed via pointer variables.
1 2 3 4 5 6 7 8 | union Employee{ int age; long salary; } *employee; (*employee).age; // or; employee->age; |
How to Access Members of a Union?
You can access members of a union using the dot (.
) operator, just like you would with structures in C. However, since all members of a union share the same memory space, you can only access one member at a time. Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> // Define a union union MyUnion { int intValue; float floatValue; char stringValue[10]; }; int main() { // Declare a union variable union MyUnion myUnion; // Access and modify members of the union myUnion.intValue = 42; printf("Integer value: %d\n", myUnion.intValue); myUnion.floatValue = 3.14; printf("Float value: %f\n", myUnion.floatValue); // Accessing char array strcpy(myUnion.stringValue, "Hello"); printf("String value: %s\n", myUnion.stringValue); return 0; } |
In this example, the MyUnion
union has three members: an integer (intValue
), a float (floatValue
), and a character array (stringValue
). You can access and modify these members using the dot operator based on the type of data you want to work with. Note that changing the value of one member will affect the other members because they share the same memory space.
Working with Array of Union
If you want to create an array of unions and work with them, you can define an array where each element is a union. Each union element can hold different types of data. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include <stdio.h> #include <string.h> // Define a union with different types union Data { int intValue; float floatValue; char stringValue[20]; }; // Define a struct to hold a union struct UnionArrayElement { int dataType; // 1 for int, 2 for float, 3 for string union Data data; }; int main() { // Define an array of unions struct UnionArrayElement myUnionArray[5]; // Populate the array with different types of data myUnionArray[0].dataType = 1; myUnionArray[0].data.intValue = 42; myUnionArray[1].dataType = 2; myUnionArray[1].data.floatValue = 3.14; myUnionArray[2].dataType = 3; strcpy(myUnionArray[2].data.stringValue, "Hello"); // Access and print the data in the array for (int i = 0; i < 3; ++i) { switch (myUnionArray[i].dataType) { case 1: printf("Integer value: %d\n", myUnionArray[i].data.intValue); break; case 2: printf("Float value: %f\n", myUnionArray[i].data.floatValue); break; case 3: printf("String value: %s\n", myUnionArray[i].data.stringValue); break; default: printf("Unknown data type\n"); } } return 0; } |
In this example, the Data
union has three members: an integer (intValue
), a float (floatValue
), and a character array (stringValue
). The UnionArrayElement
struct contains an integer dataType
to indicate the type of data stored in the union.
The program initializes an array of UnionArrayElement
and populates it with different types of data. The switch
statement is then used to determine the data type of each element in the array and print the corresponding values.
What are the Uses on Union Type?
The important use of a union is allowing access to a common location by different data types. For example hardware input and output access, bit-field and word sharing, or type punning. Unions can also provide low-level polymorphism in C++.
Unions are useful when you need to store different types of data in a compact manner. Since all members of a union share the same memory space, unions can be more memory-efficient than structures when you only need to use one member at a time.
Unions can be useful for bit-level manipulation and operations. By accessing the individual bits within a union member, you can perform bitwise operations on the data.