Define Union
Union is also same as structure. But union is a shared memory, It is possible to assign and retrieve only one member value at a time. Next member value will collapse previous member data. Memory size shall be maximum size of a member.
Example Union student{ int rno; char student_name[20]; };
For above union example allocates 20 bytes.
|
Syntax
union union_name { variables declaration; };
|
#include
//Allocates maximum memory needed by union members - 20 bytes
//Set and Get the values from union immediatly
union product {
int product_no;
char product_name[20];
float amount;
};
void main(){
union product pro;
pro.product_no = 123;
printf("%d\n",pro.product_no);
//When setting value for next member this collapse all other values of other members
//Union is a shared memory
strcpy(pro.product_name,"Dove");
printf("%d : %s",pro.product_no,pro.product_name);
pro.amount = 29.00f;
printf("%d : %s : %5.2f",pro.product_no,pro.product_name,pro.amount);
}
|
Output
123 28484 : Dove 0 : : 29.00
|