Union in C
Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.
Advantage of union over structure
it occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structuree
It can store data in one member only.
Defining union
The union keyword is used to define union. Let's see the syntax to define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
see the example to define union for student.
union student {
int id;
char name[60];
float balance;
};
Union example-1
see a simple example of union .
#include <stdio.h>
#include <string.h>
union student {
int id;
char name[60];
} s1; //declaring e1 variable for union
int main( )
{
//store first student information
s1.id=110;
strcpy(s1.name, "Pramesh gupta"); //copying string into char array
//printing first student information
printf( "student 1 id : %d\n", s1.id);
printf( "student 1 name : %s\n", s1.name);
return 0;
}
Output:
student 1 id : 1835102800
student 1 name : Pramesh gupta
As you can see, id gets garbage value because name has large memory size. So only name will have actual value.
Union example-2
#include <stdio.h>
#include <string.h>
union student {
int id;
char name[60];
} s1; //declaring e1 variable for union
int main( )
{
//store first student information
s1.id=110;
printf( "student 1 id : %d\n", s1.id);
strcpy(s1.name, "Pramesh gupta"); //copying string into char array
printf( "student 1 name : %s\n", s1.name);
return 0;
}
Output:
student 1 id : 110
student 1 name : Pramesh gupta
As you can see, id gets 110 value and name.