Tuesday 12 February 2013

Union in C++ programming Language



Union is like a structure data type in which all the members share the same memory area. The general form is,

union tag-field
{
datatype member1;
datatype member2;
------
------
datatype membern;
}variable1, variable2 ...variablen;

Example:
Consider the following union declaration
union example
{
char name[15];
int number;
}student;

This declares student as a variable to the union named example having two members. The members are accessed as
student.name
student.number
Because of the property that all members share the same memory space, the compiler allocates a memory space that is large enough to store the largest variable type in the union. In our declaration the 15 character string requires more memory than the integet quantity. so the compiler allocates 15 bytes to the union. This area will be shared by the two variables student.name and student.number.

Users of Union:

1) Unions needs less memory space
2) They are useful for applications involving number of variables, where values need not be assigned to all elements at one time

0 comments:

Post a Comment

Powered by Blogger.