Explanatory Question
What is a union?
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
Syntax of union
Let's see a simple exampleunion union_name { Member_variable1; Member_variable2; . . Member_variable n; }[union variables];
Output:#include union data { int a; //union members declaration. float b; char ch; }; int main() { union data d; //union variable. d.a=3; d.b=5.6; d.ch='a'; printf("value of a is %d",d.a); printf("\n"); printf("value of b is %f",d.b); printf("\n"); printf("value of ch is %c",d.ch); return 0; }
value of a is 1085485921 value of b is 5.600022 value of ch is a
In the above example, the value of a and b gets corrupted, and only variable ch shows the actual output. This is because all the members of a union share the common memory space. Hence, the variable ch whose value is currently updated.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.