Page 37 - Programming Microcontrollers in C
P. 37

22     Chapter 1  Introduction to C

                          has indeed kept the trust. Therefore, it is possible to assign any inte­
                          ger value to d, and the program will compile. It probably will not
                          work correctly, however.


            The Union
                              The union was invented when memory was very dear. The main
                          purpose of the union was to allow the storing of several variables at
                          a single memory location. A union has a tag name much the same
                          as the enum above.
                   union several
                   {
                       long biggie;
                       int middle_size;
                       char little,another_char;
                       short little_bigger;
                   };

                          The union several contains several members. These members
                          are not necessarily of the same type and there can be multiple in­
                          stances of the same type. To create an instance of such a union, you
                          need a definition statement. This statement can be external or imme­
                          diately following the opening of a code block, and hence local. Such
                          a statement might be
                   union several these;

                          This definition causes a union several named these to be cre­
                          ated with memory allocated. To access the members of the union,
                          you can use the dot operator as

                   these.biggie = something;
                          or

                   another = these.another_char;

                              An interesting feature of a union. If you should check the size
                          of a union, you would find that it is the size of the largest of its
                          members. Whenever you access, either read or write, a union, the
                          proper size data is written or read, and it overwrites any other data
                          that might be found in the memory location. Therefore, you can use
                          a union for storage of only one of its members at a time and writing
   32   33   34   35   36   37   38   39   40   41   42