Page 125 - 6437
P. 125

Unions

                          A union is a special data type available in C that allows to store different data types in the
                   same memory location. You can define a union with many  members, but only one member can
                   contain a value at any given time. Unions provide an efficient way of using the same memory
                   location for multiple purpose.

                          Defining a Union

                          To define a union, you must use the union statement in the same way as you did while
                   defining a structure. The union statement defines a new data type with more than one member for
                   your program. The format of the union statement is as follows:
                            union [union tag]

                            {
                                member definition;

                                member definition;
                                ...

                                member definition;
                            } [one or more union variables];

                          The union tag  is optional and each  member definition  is a  normal  variable definition,
                   such as int i; or float f; or any other valid variable definition. At the end of the union's definition,
                   before the final semicolon, you can specify one or more union variables, but it is optional. Here is
                   the way you would define a union type named Data having three members i, f, and str:
                          Now, a variable of Data type can store an integer, a floating-point number, or a string of


                 union Data
                 {

                    int i;
                    float f;

                    char  str[20];
                 } data;

                   characters. It means a single variable, i.e., same memory location, can























                                                                                                     128
   120   121   122   123   124   125   126   127   128   129   130