Explain the function and usage of a union.

Q13. Explain the function and usage of a union giving an example.

Ans. A union is a memory location that is shared by two or more different variables, generally of different types at different times. Defining a union is similar to defining a structure. Following declaration declares a union share having two variables (integer and character type) and creates a union object cnvt of union type share:

union share

{

int i;

char ch;

};

union share cnvt;

 

the keyword union is used for declaring and creating a union cnvt, both integer I and character ch share the same memory location. (of course, i (being integer) occupies 2 bytes and ch (being character) uses only 1 byte.

At any point, you can refer to the data stored in a cnvt as either an integer or a character. To assign the integer 20 to element i of cnvt, write

cnvt.i = 20;

To print the value of element ch of cnvt, write

cout<<cnvt.ch;

 

Leave a Reply

Your email address will not be published. Required fields are marked *

71 Views
%d bloggers like this: