Page 35 - Programming Microcontrollers in C
P. 35

20     Chapter 1  Introduction to C

            Other types

                              There are mechanisms for creating other types in C. The three
                          other types are enum, union, and struct. It is often quite conve­
                          nient to make use of the data types to accomplish things that are difficult
                          with the normal types available. We will see how to use these types in
                          this section.

            The enum

                              The name enum is used in C in a manner similar to the #de­
                          fine preprocessor command. The enum statement

                   enum state { OUT, IN};

                          produces the same result as
                   #define OUT 0
                   #define IN 1
                          Here, the name state is called the tag name. In this case OUT will be
                          given a value of 0 and IN a value 1. In the enum{} form, unless
                          specifically assigned, the members will be given successively increas­
                          ing values and the first will be given a value 0. Values can be assigned
                          by an enum{};
                   enum months {Jan =1,Feb, Mar, April, May, June,
                   July, Aug, Sept, Oct, Nov, Dec};
                          will cause Jan to be 1, Feb 2, and so forth up to Dec which will be 12.
                          Each member can be assigned a different value, but whenever the
                          programmer assignments stop, the values assigned to the variables
                          following will be successively increased. These values are, by de­
                          fault, of the int type. The name months in the above expression is
                          called a tag name. An enum creates a new type and you might have
                          several enums in your code that you would wish to create as in­
                          stances. The key word enum with its tag name identifies the specific
                          enum when it is used as a type identifier in a definition statement.
                              Another example
                   enum (FALSE,TRUE,Sun=1,Mon,
                   Tues,Wed,Thur,Fri,Sat);
   30   31   32   33   34   35   36   37   38   39   40