union name_of_union { member 1; member 2; . . . . . member n; };
union student s1,s2;
s1.rollno = 20; s1.mark = 90.0; printf("%d",s1.rollno);
The above code will give erroneous output. This is because we have most recently sored value in mark and we are accessing rollno. When value is assigned to a member then the value that was assigned to any other member before is lost.
union student s1 = {25}; //valid union student s1 = {80.5}; //will give undesired or erroneous output
In above example the first statement is correct while second statement will give undesired output because we are initializing second member mark (float type) of union student.
#include<stdio.h> void main() { union student { int rollno; float mark; char gender; }s1; s1.rollno=30; printf("Roll No:%d",s1.rollno); s1.mark=92.5; printf("nMark:%f",s1.mark); s1.gender='Male'; printf("nGender:%c",s1.gender); }
Roll No=30 Mark=92.5 Gender=Male