Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C

Learn step by step



C-Union

Unions are quite similar to the structures in C. As structure union is also a derived type. It can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct.

union car{
char name[50];
int price;
};

Union variables can also be created in similar manner as structure variable.

union car{
char name[50];
int price;
}c1, c2, *c3;
OR;
union car{
char name[50];
int price;
};
-------Inside Function-----------
union car c1, c2, *c3;

In both cases, union variables c1, c2 and pointer variable c3 of type union car is created.

Accessing members of an union

The member of unions can be accessed in similar manner as structure. Suppose that we you want to access price for union variable c1 in the above example, then it can be accessed as c1.price. And if you want to access price for union pointer variable c3, then it can be accessed as (*c3).price or as c3->price.

Difference between union and structure

Though unions are similar to structure in so many ways, the difference between them is vital to understand. This can be demonstrated by given example:


#include <stdio.h>
union job { //defining a union
char name[32];
float salary;
int worker_no;
}u;
struct job1 {
char name[32];
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
} RUN

There is difference in memory allocation to members between union and structure as suggested in above example. The amount of memory required to store any structure variables is the sum of memory size of all members.

But, the memory required to store any union variable is the memory required for largest element of an union.

What difference does it make between union and structure?

As you know, all members of structure can be accessed at any time. But, only 1 member of union can be accessed at a time and at this time other members of union will contain garbage value.


#include <stdio.h>
union job {
char name[32];
float salary;
int worker_no;
}u;
int main(){
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}

Output

Enter name
tuton
Enter salary
10232.23
Displaying
Name: f%Bary
Salary: 10232.23

Note that you may get different garbage value of name.

Why this output?

Initially, tuton will be stored in u.name and other members will contain garbage value. But when user enters the value of salary, 10232.23 will be stored in u.salary and other members will contain garbage value. Thereby in output, salary is printed accurately but name displays some random string.



Related Videos