- Union is an user defined datatype in C programming language.
- It is a collection of variables of different datatypes in the same memory location.
- We can define a union with many members, but at a given point of time only one member can contain a value.
- Unions can be very handy when you need to talk to peripherals through some memory mapped registers.
Need for Union in C programming :
C unions are used to save memory. To better understand an union, think of it as a chunk of memory that is
used to store variables of different types. When we want to assign a new value to a field, then the existing data
is replaced with new data.
C unions allow data members which are mutually exclusive to share the same memory. This is quite important
when memory is valuable, such as in embedded systems. Unions are mostly used in embedded programming
where direct access to the memory is needed.
How to define a union?
We use the union keyword to define unions. Here’s a Syntax:
union unionName { //member definitions };
Examples:-
union Courses { char WebSite[50]; char Subject[50]; int Price; };
Accessing Union Members in C Example :
#include<stdio.h> #include<string.h> union Courses { char WebSite[50]; char Subject[50]; int Price; }; void main( ) { union Courses C; strcpy( C.WebSite, "Topperworld.in"); printf( "WebSite : %s\n", C.WebSite); strcpy( C.Subject, "The C Programming Language"); printf( "Book Author : %s\n", C.Subject); C.Price = 0; printf( "Book Price : %d\n", C.Price); }
Output:-
WebSite : Topperworld.in
Book Author : The C Programming Language
Book Price : 0
Advantages of union:
- It occupies less memory compared to structure.
- When you use union, only the last variable can be directly accessed.
- Union is used when you have to use the same memory location for two or more data members.
- It enables you to hold data of only one data member.
- Its allocated space is equal to maximum size of the data member.
Disadvantages of union :
- You can use only one union member at a time.
- All the union variables cannot be initialized or used with varying values at a time.
- Union assigns one common storage space for all its members.