Page 152 - C-Language
P. 152

Chapter 20: Enumerations




        Remarks



        Enumerations consist of the enum keyword and an optional identifier followed by an enumerator-list
        enclosed by braces.

        An identifier is of type int.


        The enumerator-list has at least one enumerator element.

        An enumerator may optionally be "assigned" a constant expression of type int.


        An enumerator is constant and is compatible to either a char, a signed integer or an unsigned
        integer. Which ever is used is implementation-defined. In any case the type used should be able to
        represent all values defined for the enumeration in question.

                                                                                   st
        If no constant expression is "assigned" to an enumerator and it is the 1  entry in an enumerator-
        list it takes value of 0, else it get takes the value of the previous entry in the enumerator-list plus 1.


        Using multiple "assignments" can lead to different enumerators of the same enumeration carry the
        same values.


        Examples



        Simple Enumeration


        An enumeration is a user-defined data type consists of integral constants and each integral
        constant is given a name. Keyword enum is used to define enumerated data type.

        If you use enum instead of int or string/ char*, you increase compile-time checking and avoid
        errors from passing in invalid constants, and you document which values are legal to use.


        Example 1



         enum color{ RED, GREEN, BLUE };

         void printColor(enum color chosenColor)
         {
             const char *color_name = "Invalid color";
             switch (chosenColor)
             {
                case RED:
                  color_name = "RED";
                  break;

                case GREEN:
                 color_name = "GREEN";




        https://riptutorial.com/                                                                             128
   147   148   149   150   151   152   153   154   155   156   157