C Programming Unions Assignment Help
Unions
Union is one of the user defined data type. It is also used to pack different type of data items into a single unit.
Difference between structure and union
C Programming Unions Assignment Help By Online Tutoring and Guided Sessions from assignmenthippo.com
Each member of structure have their one memory location. In union, all members share same memory location.
Example:
Structure:
struct emp
char x; //1 byte
float a; //4 bytes
e;
Union
union emp
char x; //1 byte
float a; //4 bytes
e;
Explanation:
In structure for the structure variable ‘e’ 5 bytes of memory is allocated in such a way that, 1 byte for x and 4 byes for a. In union, among the members more memeory requirement is allocated,such a way that among int and float float requires more memory space (4 bytes). For union, 4 bytes are allocated to share all union memebers.
Defining a Union
The task of packing different types of data items into a single unit is defining union.
Syntax:
union [union tag]
member-1 definition;
member-2 definition;
...
member-n definition;
[one or more union variables];
Example:
union emp
int empid;
char name[20];
char dep[50];
e;
Accessing Union Members
Union members are accessed using (.) dot operator.
Example:
#include <stdio.h>
#include <string.h>
union emp
int empid;
char name[20];
char dept[50];
;
int main( )
union emp e;
e.empid=10;
strcpy(e.name, "Ram”);
strcpy( e.dept, "Testing");
printf(“Given details are:\n”);
printf( "Employee id : %d\n", e.empid);
printf( "Employee Name: %s\n", e.name);
printf( "Department : %s\n", e.dept);
return 0;
Output:
Given details are:
Employee id:10
Employee Name:Ram
Department :Testing