Page 36 - Programming Microcontrollers in C
P. 36

Other Types      21

                          will result in FALSE being 0, TRUE 1, Sun 1, Mon 2, and so
                          forth to Sat 7. Note that it is not necessary to assign a tag name to
                          an enum.
                              An enum is typed at declaration time. Therefore, the values cre­
                          ated by an enum are indeed numerical values. This differs from the
                          #define because the statement
                   #define FALSE 0

                          will cause the character ‘0’ to be inserted into the source code when­
                          ever the label FALSE is encountered. As such, the #defineconstruct
                          is a character substitution  technique or a macro expansion. The re­
                          sult of an enum is a numerical substitution. The #define construct,
                          being a simple character substitution, has no typing attached to its
                          arguments. Constants created by an enum are typed, and therefore,
                          will avoid many of the potential hazards of dealing with untyped
                          variables.
                              Let us examine how one might use a type created with an enum
                          construct. The following enum defines two constants

                   enum direction {LEFT,RIGHT};
                          In a program, a definition statement

                   enum direction d;
                          will cause a variable d to be created. The acceptable values for d are
                          the names LEFT and RIGHT. We know, of course, that the numerical
                          value for LEFT is 0 and the value for RIGHT. Within your program,
                          you can assign and test the value of d. For example,

                   if(d==LEFT)
                       do something

                          or
                   if(d==RIGHT)
                              do something else

                          or
                   d = RIGHT;

                          As stated earlier, the acceptable values for d are LEFT and RIGHT.
                          There is no checking within the program to see if the programmer
   31   32   33   34   35   36   37   38   39   40   41