Article by: Manish Methani
Last Updated: November 1, 2021 at 2:04pm IST
Unions are a type of data structure in C programming that allow you to store different types of data in the same memory space. In this tutorial, we will cover what unions are, how to create them, and how to use them in your code with practical examples and explanations.
To create a union in C programming, you use the same syntax as creating a struct, but use the keyword union instead of struct. Here is an example of how to create a union:
#include <stdio.h> union data { int i; float f; char str[20]; }; int main() { union data d1; d1.i = 10; printf("d1.i = %d", d1.i); d1.f = 3.14; printf("d1.f = %.2f", d1.f); strcpy(d1.str, "Hello"); printf("d1.str = %s", d1.str); return 0; }
In the above example, we define a union named data with three members: an integer, a float, and a character array. We then create a variable d1 of type union data and assign a value to its integer member. We then print the value of d1.i. Next, we assign a value to the float member of d1 and print it. Finally, we assign a string to the character array member of d1 and print it.
Unions are useful when you want to store different types of data in the same memory space. Here is an example of how to use a union to store a value of different types:
#include <stdio.h> union data { int i; float f; }; void print_data(union data d, int type) { if (type == 0) { printf("Data as integer: %d", d.i); } else if (type == 1) { printf("Data as float: %.2f", d.f); } } int main() { union data d1; d1.i = 10; print_data(d1, 0); // pass union as integer d1.f = 3.14; print_data(d1, 1); // pass union as float return 0; }
In the above example, we define a union named data with two members: an integer and a float. We then define a function named print_data that takes a union data variable and a type parameter. If the type parameter is 0, the function prints the value of the integer member. If the type parameter is 1, the function prints the value of the float member. We then create a variable d1 of type union data and assign a value to its integer member. We then call the print_data function twice with d1 and pass a different type parameter each time.
In this tutorial, we have covered what unions are, how to create them, and how to use them in your C programming code with practical examples and explanations. By understanding unions, you can create more flexible data structures that can store different types of data in the same memory space. Improve your programming skills today by experimenting with unions in your code.