Unions in C


Union is another way to group data items of different types. It is a block of memory that is used to hold data items of different types. On may think that it is similar to structures to structures that we discussed in previous section, as structures also hold different types of data items. But they are different from structures.
            All the members of the union share the same storage area within computer memory where as in case of a structure each member is assigned its unique storage area. Thus unions are used to conserve memory. In this case, memory assignment is that much that is required to access the largest members of structure.

General Syntax:



Here, union is a keyword that specifies the union data type item is the tag name of the union. It is used by the compiler to identify the union. The variables a,b and c are the members of the union and are declared within the curly braces. The union declaration ends with a semicolon.

Referring a Union Member
Union members can be referred in the same manner as structure members. We can refer union members either using a dot (.) operator or arrow (- >) operator. 

Previous                                                                                    Next


Powered by Blogger.