Union in c language
- It is a collection of data of different data type.
- It is a user defined data type.
- Data can of int,char,float,double etc. data type.
- We can access the member of union by making the variable of structure.
- union keyword is used to create a union.
Note :- Union does not support multiple value simultaneously and it can store only one value at a time.
syntax:
union union_name
{
data_type variable 1;
data_type variable 2;
};
p>Example:
union student
{
char name[100];
int rollno;
float marks;
};
ul class="list">
Here student is the name of union.
union is a keyword
Declaration of union variable method 1
union student
{
char name[100];
int rollno;
float marks;
};
void main( )
{
union student student1;
};
Here student1 is the variable of union.
Declaration of union variable method 2
union student
{
char name[100];
int rollno;
float marks;
}student1;
int main( )
{
return 0;
}
Accessing the data members of union :
The data member of union can be accessed as union_variable.data member
for example if we want to access the rollno of student then we can write as student1.rollno
example – write a program to store and display the student name,rollno and marks.
Note :- But Union will show only last value correct because it can store only single value at a time.
I am writing this program here so that you can understand diffrence between structer and union better.
#include< stdio.h >
>#include< string. h >
union student
{
char name[100];
int rollno;
float marks;
};
void main( )
{
unionstudent student1;
(strcpy(student1.name,"Aditya");
student1.rollno = 07;
student1.marks = 80.5;
printf("Student name = %s \n",student1.name);
printf("Student rollno = %d \n",student1.rollno);
printf("Student marks = %f \n",student1.marks);
}
Output:
Student name = Aditya
Student rollno = 07
Student marks = 85.5