Professional Documents
Culture Documents
Defining a Union
To define a union, you must use the union statement in the same
way as you did while defining a structure. The union statement
defines a new data type with more than one member for your
program.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as
follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the
members’ names and data types along with the name of the union. No memory
is allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};
Initialization of Union in C
union Data
{
int i;
float f;
char str[20];
} data;
You can use any built-in or user defined data types inside a union
based on your requirement.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
#include <stdio.h>
int main()
{
#include <stdio.h>
#include <string.h>
Union Data
{
int i;
float f;
char str[20];
};
int main( )
{
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
}
Understanding the Difference Between Structure and
Union in C
Total Size Sum of sizes of all members. Size of the largest membe
Can store values for all members Can store value for only o
Data Storage
simultaneously. member at a time.
Accessing All members can be accessed at any Only the last stored memb
Members time. be accessed.
Modification Modifying a member doesn’t affect Modifying one member m
Impact other members. overwrite other members.