Union in C Language

Hello friends how are you, today in this blog i will teach you what is union, syntax of union, how union works and many programs of union in a very simple way.

Let's start

1.It is a collection of data of different data type.
2.It is a user defined data type.
3.Data can be of int, char, float, double etc. data type.
4.We can access the member of union by making the variable of union.
5.union keyword is used to create a union.
6.The difference between structure and union is that structure can store multiple value simultaneously but union can store only one value at a time.
7.The region is that in structure each member of structure has its own memory space but in union a single memory space is shared by all members of union.

👉Syntax

👉Example  

union student
{
 char name[200];
 int rollno;
 float marks;
};
1.Here student is the name of union.
2.union is a keyword. 

👉Declaration of union variable method 1 

union student
{
 char name[200];
 int rollno;
 float marks;
};
int main()
{
union student student1;
return 0;
}
Here student1 is the variable of union. 

👉Declaration of structure variable method 2 

union student
{
 char name[200];
 int rollno;
 float marks;
}student1;
int main()
{
return 0;
}
Here student1 is the variable of union. 

👉Accessing the data members of structure  The data member of structure 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 student information

#include<stdio.h>
#include<string.h>
union student
{
 char name[200];
 int rollno;
 float marks;
};
int main()
{
union student student1;//creating union variable
strcpy(student1.name,"Lucky");
student1.rollno=201;
student1.marks=85.9;
printf("Student Name =%s\n",student1.name);
printf("Student Rollno=%d\n",student1.rollno);
printf("Student Marks=%f\n",student1.marks);
}
/*
### Output ###
Student Name=garbage value
Student Rollno=garbage value
Student Marks=85.900002
*/

Here the above program will display only marks of student correctly because union can store only single data at a time

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 

If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

Thanks.😊

Post a Comment

0 Comments