C Union is also like structure, i.e.
collection of different data types which
are grouped together. Each element in a union is called member.
Union and structure in C are same in concepts, except allocating
memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its
members
We can access only one member of union at a time. We can’t access all
member values at the same time in union. But, structure can access all
member values at the same time. This is because, Union allocates one
common storage space for all its members. Where as Structure allocates
storage space for all its members separately.
Many union variables can be created in a program and memory will be
allocated for each union variable separately.
Below table will help you how to form a C union, declare a union,
initializing and accessing the members of the union.
Type Using normal variable Using pointer variable
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
Syntax
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
union student union student
{ {
int mark; int mark;
Example
char name[10]; char name[10];
float average; float average;
}; };
Declaring
union student report; union student *report, rep;
union variable
Initializing union student report = union student rep = {100,
union variable {100, “Mani”, 99.5}; “Mani”, 99.5};report = &rep;
report.mark report -> mark
Accessing
report.name report -> name
union members
report.average report -> average
Example program for C union:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n",
record1.subject);
printf(" Percentage : %f \n\n",
record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n",
record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n",
record2.percentage);
return 0;
}
Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
A union is a special data type available in C that enables you to store
different data types in the same memory location. You can define a union
with many members, but only one member can contain a value at any given
time. Unions provide an efficient way of using the same memory location for
multi-purpose.
Defining a Union
To define a union, you must use the union statement in very similar was as
you did while defining structure. The union statement defines a new data
type, with more than one member for your program. The format of the union
statement is as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At
the end of the union's definition, before the final semicolon, you can specify
one or more union variables but it is optional. Here is the way you would
define a union type named Data which has the three members i, f, and str:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or
a string of characters. This means that a single variable ie. same memory
location can be used to store multiple types of data. You can use any built-in
or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in above example Data type will occupy
20 bytes of memory space because this is the maximum space which can be
occupied by character string. Following is the example which will display
total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n",
sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following
result:
Memory size occupied by data : 20
Accessing Union Members
To access any member of a union, we use the member access operator (.).
The member access operator is coded as a period between the union variable
name and the union member that we wish to access. You would use union
keyword to define variables of union type. Following is the example to
explain usage of union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following
result:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that values of i and f members of union got corrupted
because final value assigned to the variable has occupied the memory
location and this is the reason that the value if str member is getting printed
very well. Now let's look into the same example once again where we will
use one variable at a time which is the main purpose of having union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following
result:
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is
being used at a time.
Unions in C Language
Unions are conceptually similar to structures. The syntax of union is also
similar to that of structure. The only differences is in terms of storage. In
structure each member has its own storage location, whereas all members of
union uses a single shared memory location which is equal to the size of its
largest data member.
This implies that although a union may contain many members of different
types, it cannot handle all the members at same time. A union is declared
using union keyword.
union item
{
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three
members each with a different data type. However only one of them can be
used at a time. This is due to the fact that only one location is allocated for a
union variable, irrespective of its size. The compiler allocates the storage that
is large enough to hold largest variable type in the union. In the union
declared above the member x requires 4 bytes which is largest among the
members in 16-bit machine. Other members of union will share the same
address.
Accessing a Union Member
Syntax for accessing union member is similar to accessing structure member,
union test
{
int a;
float b;
char c;
}t;
t.a ; //to access members of union t
t.b ;
t.c ;
Complete Example for Union
#include < stdio.h>
#include < conio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
return 0;
}
Output :
-26426
20.1999
z
As you can see here, the values of a and b get corrupted and only variable c
prints the expected result. Because in union, the only member whose value
is currently stored will have the memory.