Unions
As array represent group of data items that belong to the same type. C supports a constructed data type known as structure and unino, which are methods for packing data of different types. These are used to organize complex data in more meaninigful way. Unions are a concept borrowed from structures and therefore follow the same syntax as structures and unions arise in terms of storage. In structure each member has its own storage location. Where as all the members of a union use the same location. Although a union may contain many members of different types,it can handle only one member at a time.
Ex:
union item
{
int m;
float x;
char c;
};
union item code;
The word item is called union tag. The union declaration must end with semicolon. The union contain three members each with a different data type. However, we can use only one of them at a time.This is due to the fact that only one location is allocated for a union variable, irrespective of its size. Among all datatypes of variables that are declared in union, the variable type that has maximum size is the size allocated to union. In above example, the float has maximum size 4 bytes. Hence the size of union item has 4 bytes. To access union member (m/x/c) we have to use dot operator
code is the variable i.e declared of type item. Remember that the members of union themselves are not variables.They dont occupy any memory until they are associated with union
variable such as code.
In defining union/structure, we have to note following syntax.
1.The template is terminated with semicolon.
2.While the entire declaration is considered as a statement,each member is declared independently for its name and type in a seperate statement inside the template.
3.The tagname code can be used to declare union variables of its type, later in the program. To access union member, we can use
code.m=379;
code.x=759.76;
printf("%d", code.m);
A union creates a storage location that can be used by anyone of its members at a time. When a different members is assigned a new value, the new value supercodes the previous value.Union
may be used in all places where a structure is allowed.
0 comments:
Post a Comment