C/Data Type/Union
Simple union
<source lang="cpp"> union marks {
float perc; char grade;
} main () {
union marks student1; student1.perc = 98.5; printf( "Marks are %f address is %16lu\n", student1.perc, &student1.perc); student1.grade = "c"; printf("Grade is %c address is %16lu\n", student1.grade, &student1.grade);
}
</source>
The operation of a union
<source lang="cpp">
- include <stdio.h>
void main() {
union u_example { float decval; int pnum; double my_value; } U1; U1.my_value = 125.5; U1.pnum = 10; U1.decval = 1000.5f; printf("\ndecval = %f pnum = %d my_value = %lf", U1.decval, U1.pnum, U1.my_value ); printf("\nU1 size = %d\ndecval size = %d pnum size = %d my_value size = %d", sizeof U1, sizeof U1.decval, sizeof U1.pnum, sizeof U1.my_value);
}
</source>