2. Defination & introduction
• Unions are con conceptually similar to structures
• The syntax of union is also similar to that of structure
• The only difference is in term of storage
• In structure each member has its own storage location where
the all members of union uses a single shared memory
location which is equal to the size of its largest data
member .
• Data can of int,char,float,double etc .data type
• It is a user defined data type
Note-> union does not support multiple value it can store
only one value at a time
•
3. structure union
Struct emp; union emp
{ {
Char x; //size 1 byte char x;
Float y;//size 4 byte float y;
}e;}e; memory sharing
x y x&y
5 byte 4 byte
4. syntax
Keyword→ union structure _ name
{
data_ type variable 1;
Body data_type variable 2;
…………………………….
data _type variable n;
};
6. Declaration of union variable
method 1
Union student
{
Char name[200];
Int roll no;
Float marks;
};
Int main()
{
Union student student1;
Return 0;
}
7. Declaration of union variable
method 2
Union student
{
Char name[200];
Int rollno;
Float marks;
}student1;
Int main()
{
Return 0;
}
8. Accessing the data members of
union
• The data member of union can be
accessed as
Union_variable.data_mamber
Example
The rollno of student then we can write as
Student1.rollno
9. Program of union• #include<stdio.h>
• #include<string.h>
• union student
• {
• char name[200];
• int rollno;
• float marks;
•
• }student1;
• int main()
• {
•
• strcpy(student1.name,"ali");
• student1.rollno=201;
• student1.marks=78.5;
• printf("student name=%sn",student1.name);
• printf("student roll no=%dn",student1.rollno);
• printf("student marks=%fn",student1.marks);
• return 0;
• }
10. Program of union• #include<stdio.h>
• #include<string.h>
• union student
• {
• char name[200];
• int rollno;
• float marks;
•
• }student1;
• int main()
• {
•
• strcpy(student1.name,"ali");
• student1.rollno=201;
• student1.marks=78.5;
• printf("student name=%sn",student1.name);
• printf("student roll no=%dn",student1.rollno);
• printf("student marks=%fn",student1.marks);
• return 0;
• }