Union in C
A union is a special data type that allows storing different data types in the same memory location. We can illustrate a union with many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for different data types.
The union statement defines a new data with more than one member for the program. The format of statement is as follows:
Syntax:
union union_name {
data_type member 1;
data_type member 2;
.
.
data_type member n;
} [one or more union variables];
Advantage of union
Union occupies less memory.
Disadvantage of union
Last entered data only available in the union because it overwrites previous data memory.
Example:
#include <stdio.h>
#include <stdlib.h>
union student
{ int id;
char name[50];
float mark1;
}s;
void main( )
{
s.id=101;
printf( "Student 1 id : %d\n", s.id);
strcpy(s.name, "Arunkumar");
printf( "Student 1 name : %s\n", s.name);
s.mark1=89;
printf( "Student 1 mark1 : %f\n", s.mark1);
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com