union in c programming example
What is union in C?
Union is an user defined datatype in C programming language. It is a collection of variables of different datatypes in the same memory location. We can define a union with many members, but at a given point of time only one member can contain a value. ... C unions are used to save memory.
1.Union and structure in C are same in concepts, except allocating memory for their members.
2.Structure allocates storage space for all its members separately.
3.Whereas, Union allocates one common storage space for all its members
4.We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.
5.Many union variables can be created in a program and memory will be allocated for each union variable separately.
6.Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
Example union in c programming:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
No comments:
Post a Comment