简体   繁体   中英

typedef enum, assiging a value within

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,

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)

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.

Why have the type_count and why assign type_count to type_unknown?

To keep a tab on the maximum allowed value for an enum . Remember, there'd be otherwise no way to check if a given value is correct (within the range) or not.

TYPE_COUNT can serve to dimension an array indexed by the enum's elements:

type_info my_info[TYPE_COUNT]; 

or can be used in an exit condition of a for loop. TYPE_UNKNOWN can be used to represent an illegal or undefined value for the type (-1 could be an alternative to TYPE_COUNT for it's value).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM