Unions
In
C Language
Made By :
Ishmeet Kaur ((12413202724)
Jasnoor Kaur (12513202724)
Hargun Kaur Grover (13513202724)
Isharpreet Kaur (14313202724)
About Union
DEFINITION PURPOSE
A union is a user- Unions provide an
defined data type efficient way to
that allows storing use memory when
different data types only one of the
in the same memory variables is
location. needed at a time.
Structure
Vs
Union
Structure Union
Share the same memory Allocate separate memory for
space for all members. each member.
The size of the union is The size is the sum of the
determined by its largest sizes of all members.
member.
Syntax
union UnionName
{
data_type1 member1;
data_type2 member2; #include <stdio.h>
union Data {
int intVal ;
} float floatVal;
char charVal;
}
int main() {
union Data data ;
data.intVal = 10 ;
printf("intVal: %d\n", data.intVal);
data.floatVal = 3.14;
printf("floatVal: %f\n", data.floatVal);
data.charVal = 'A';
Advantages of
Using Unions
Memory Efficiency: Useful for Embedded
Systems:
Only one member can
be accessed at a time, Ideal for applications
saving memory space. where memory is
limited.
Limitations of
Using Unions
Single Active Member: Data Integrity:
You can only use one Overwriting one
member at a time. member destroys the
data of the other
members.