Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef enum, assiging a value within

Tags:

c

enums

compiling with gcc C99

I have been using enums for a while now. However, I am using some sample code to develop my application. And I came across some code like this. I have been informed this is the best practice use when using enums. But I don't see how this has any advantages.

typedef enum {
    TYPE_DATE,
    TYPE_TIME,
    TYPE_MONEY,

    TYPE_COUNT,
    TYPE_UNKNOWN = TYPE_COUNT
} string_type_e;

Why have the TYPE_COUNT and why assign TYPE_COUNT to TYPE_UNKNOWN?

Many thanks for any suggestions,

like image 214
ant2009 Avatar asked Mar 29 '09 15:03

ant2009


2 Answers

By default, enums are automatically given integer values starting from 0 by the compiler. So date will be zero, time one and money two. The next value is given to the 'psuedo' enum value TYPE_COUNT, which will get given the value three, which happens to be the number of 'proper' enum values.

TYPE_UNKNOWN is another value which represents something which isn't a 'proper' value, so will fail a test e < TYPE_COUNT. Having it equal to TYPE_COUNT means that each distinct meaningful value is contiguous, but I'm not aware of any significant advantage to that (there would be if TYPE_COUNT was one less than a power of 2, which might effect what representation the compiler could use, and its 'nice' to have the values contiguous, but it doesn't really matter, as you wouldn't increment them past TYPE_COUNT anyway)

like image 164
Pete Kirkham Avatar answered Nov 05 '22 07:11

Pete Kirkham


Enum values are basically integer constants. By default they are given the value of last element in the enum + 1 (and 0 for the first element). When you want to count the elements, which might be useful for mapping it with an array or something, of the enum declared like that (that will be updated dynamically if you add or remove something from it), you can put a COUNT constant at the end of it (TYPE_COUNT in your example). To be able to distinguish invalid values in the enum, you might want to declare another constant. In your example, that constant will be equal to the count constant, which is one value bigger than the largest value of your enum.

like image 25
mmx Avatar answered Nov 05 '22 05:11

mmx