Like structures, unions also contain members whose individual data types may differ from one another.However, the members of a union share the same storage area within the computer's memory, whereas each members within a structure is assigned its own unique storage area.thus, unions are used to conserve memory.They are useful for applications involving multiple members, where values need not be assigned to all of the members at any one time.
In general terms, the composition of a union may be defined as
union tag {
member 1;
member 2;
...............
member n;
};
where union is a required keyword and other terms have the same meaning as in a structure definition. Individual union variables may be defined as
storage-class union tag variable 1,variable 2,............,variable n;
where storage-class is an optional storage class specifier, union is a required keyword, tag is the name that appeared in the structure declaration, and variable 1,variable 2,............,variable n are structure variables of type tag.
The two declarations can be combined, just as we did with structures. Thus, we can write
storage-class union tag {
member 1;
member 2;
...............
member n;
}variable 1,variable 2,............,variable n;
The tag is optional in this situation.
Let us consider the simple C program shown below.
#include < stdio.h >
main()
{
union id {
char color;
int size;
};
struct {
char manufacture[20];
float cost;
union id description;
} shirt, blouse;
printf("%d\n", sizeof(unionid));
/*assign a value to color*/
shirt.description.color = 'w';
printf("%c %d\n", shirt.description.color, shirt.description.size);
/*assign a value to size*/
shirt.description.size = 12;
printf("%c %d\n", shirt.description.color, shirt.description.size);
}
Execution of the program results n the following output.
2
w -24713
@ 12
The first line indicates that the union is allocated two bytes of memory, to accommodate an integer quantity.In line 2, the first data item (w) is meaningful, but the second (-24713) is not.In line 3, the first data item (@)is meaningless, but the second data (12) item has a meaning.Thus, each data item has a meaningful value in accordance with the assignment statement preceding each printf statement.
Friday, January 8, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment