In C, a union is a type of data structure that allows you to store different data types in the same memory location. A union is similar to a structure, but it only allows one member to be active at a time. The size of a union is the size of its largest member.
Syntax :
union union_name
{
datatype member_1 ;
datatype member_2 ;
datatype member_n ;
}
This program demonstrates the use of union in C programming language.
This program is a simple example of how to use union in C and how to access the members of a union, it also demonstrates the difference in memory usage between union and struct.
//Union in C Programming #include<stdio.h> /* 1.User Define Data Type 2.Union Members Share the Same Memory Location 3.Union Size is based in biggest size of a data type */ struct demo { int a;//4 char b; }; union udemo { int a;//4 char b; }o; int main() { /* printf("\nInteger : %d",sizeof(int)); printf("\nchar : %d",sizeof(char)); printf("\nUnion Size : %d",sizeof(union udemo)); printf("\nStruct Size : %d",sizeof(struct demo));*/ o.a=65; printf("\nUnion A : %d",o.a); printf("\nUnion B : %c",o.b); return 0; }To download raw file Click Here
Union A : 65 Union B : A
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions