Create and use Union in C Programming.
Union: As we learned in previous tutorials that a union is one of a special data type available in C language that allows us to store different types of data in the same memory location.
Many members of union can be defined but only one member can contain value at a time.The use of union is to provide an efficient way of using same memory location for various purposes.
Following is syntax to create union in C programming.
1.
union union_name {
datatype member1;
datatype member2;
...
};
2.
union union_name {
datatype member1;
datatype member2;
...
}u1;
Note: Union Declaration is always ends with semicolon ;
Create and Use Union in C.
From the given fig. Let understand how to create and use union variable in c programming Language.we have defined union name emp with its members int empno,char ename and float salary.Here we are creating union variable and demonstrate how to use it.
From the Given fig. We can study how to declare union?, How to create union Variable?.
finally How to assign values to union member and access or use the union members.
1. Declare Union:
union emp
{
int empno;
float salary;
char ename[20];
};
The given above is the way we have declared a union type named emp having three members empno, salary, and ename.
2. Union Variable Creation,Assigning Value and Acessing or use union Members:
union emp e;
e.empno=1090;
printf("\nEmpno=%d",e.empno);
e.salary=34589.34;
printf("\nSalary=%.2f",e.1salary);
strcpy(e.ename,"Raj");
printf("\n Name=%s",e.ename);
Here Union Variable e can store an integer,a floating-point number and a string of characters.That means a single union variable e use same memory location to multiple types of data members.The user can use any user defined of any built-in data types inside union depending upoun users requirements.
The memory occupied by union variable is the size of the largest member size of the union member.
For example, in the above example, emp type will occupy 20 bytes of memory space,because the union character member ename occupies the maximum space .
#include<stdio.h>
#include<string.h>
union emp{
int empno;
float salary;
char ename[20];
};
int main(){
union emp e;
printf("\n Size occupied by emp=%d Bytes.",sizeof(e));
return(0);
}
Output:
Size occupied by emp=20 Bytes.
Example to Create and Use Union in C Language.
#include<stdio.h>
#include<string.h>
union emp{
int empno;
float salary;
char ename[20];
};
int main(){
union emp e;
e.empno=1090;
printf("\nEmpno=%d",e.empno);
e.salary=34589.34;
printf("\nSalary=%.2f",e.salary);
strcpy(e.ename,"Raj");
printf("\n Name=%s",e.ename);
return(0);
}
Output:
Empno=1090
Salary=34589.34
Name=Raj