union is a user-defined
data type
Note:
It is the collection of
different data elements
union keyword is used to
define a structure
dot operator(.) is used
for accessing members.
When a variable is
associated with a union, the compiler allocates the memory by
considering the size of the largest memory. So size of union is
equal to the size of largest member
Only one member can be
accessed at a time.
Syntax:
union[union name]
{
Member definition;
Member definition;
..
Member definition
};
Example:
union Employee
{
char
name[50]; //1byte memory
int
id;
//2 byte
float salary;
//4byte
} e1;
Note:
4
bytes memory is allocated because the compiler allocates the memory in union by considering the size of the largest memory
Example 1(1st
way):
#include
<stdio.h>
#include<string.h>
#include<conio.h>
union
Employee
{
char name[50];
int id;
float salary;
};
void
main()
{
union Employee e1;
e1.id=1;
clrscr();
strcpy(e1.name, "Suryosnata");
e1.salary =35000.45;
printf(" Name is: %s \n", e1.name);
printf(" Id is: %d \n", e1.id);
printf(" Salary is: %f \n",
e1.salary);
getch();
}
Output:
Name is: sGosnata
Id is: 1191753843
Salary is: 35000.449219
Example 1(2nd
way):
#include
<stdio.h>
#include<conio.h>
union
Employee
{
char name[50];
int id;
float salary;
};
void
main()
{
union
Employee e1={"suryosnata",1,35000.45};
printf(" Name is: %s \n",
e1.name);
printf(" Id is: %d \n",
e1.id);
printf(" Salary is: %f
\n", e1.salary);
getch();
}
Output:
Name is: suryosnata
Id is: 2037544307
Salary is: 78682374557984041996425324851625984.000000
Example 2(Taking value from user)
#include <stdio.h>
#include<conio.h>
union Employee
{
char name[50];
int id;
float salary;
} e1;
void main()
{
clrscr();
printf("Enter
Employee information:\n");
printf("Enter NAME:
");
scanf("%s",
e1.name);
printf("Enter ID:
");
scanf("%d",
&e1.id);
printf("Enter SALARY:
");
scanf("%f",
&e1.salary);
printf("Employee
Information:\n");
printf("Name:
%s\n",e1.name);
printf("Id:
%d\n",e1.id);
printf("Salary: %f\n", e1.salary);
printf("Salary: %f\n", e1.salary);
getch();
}
Enter Employee information:
Enter NAME: surya
Enter ID: 101
Enter SALARY: 12456
Employee Information:
Name:
Id: 1178771456
Salary: 12456.000000
Only
salary is displayed here because the compiler allocates the memory by
considering the size of the largest memory (salary is the largest size)
No comments:
Post a Comment