CS3251 (UNIT 4) NOTES EduEngg
CS3251 (UNIT 4) NOTES EduEngg
CONNECT WITH US
WEBSITE: www.eduengineering.in
TELEGRAM: @eduengineering
Union
Union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also be defined as
many members, but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory
location.
Syntax
union union name
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
Output :
data.i : 10
data.f : 220.500000
data.str : C Programming
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
Output : 90