Number of elements in an enum

后端 未结 8 2297
抹茶落季
抹茶落季 2020-12-05 02:06

In C, is there a nice way to track the number of elements in an enum? I\'ve seen

enum blah {
    FIRST,
    SECOND,
    THIRD,
    LAST
};

相关标签:
8条回答
  • 2020-12-05 02:39
    #include <stdio.h>
    
    // M_CONC and M_CONC_ come from https://stackoverflow.com/a/14804003/7067195
    #define M_CONC(A, B) M_CONC_(A, B)
    #define M_CONC_(A, B) A##B
    
    #define enum_count_suffix _count
    #define count(tag) M_CONC(tag, enum_count_suffix)
    #define countable_enum(tag, ...) \
      enum tag {__VA_ARGS__}; \
      const size_t count(tag) = sizeof((int []) {__VA_ARGS__}) / sizeof(int)
    
    // The following declares an enum with tag `color` and 3 constants: `red`,
    // `green`, and `blue`.
    countable_enum(color, red, green, blue);
    
    int main(int argc, char **argv) {
      // The following prints 3, as expected.
      printf("number of elements in enum: %d\n", count(color));
    }
    
    0 讨论(0)
  • 2020-12-05 02:42

    Old question, I know. This is for the googlers with the same question.

    You could use X-Macros

    Example:

    //The values are defined via a map which calls a given macro which is defined later
    #define ENUM_MAP(X) \
          X(VALA, 0)    \
          X(VALB, 10)   \
          X(VALC, 20)
    
    //Using the map for the enum decl
    #define X(n, v) [n] = v,
    typedef enum val_list {
        ENUM_MAP(X) //results in [VALA] = 0, etc...
    } val_list;
    #undef X
    
    //For the count of values
    #define X(n, v) + 1
    int val_list_count = 0 + ENUM_MAP(X); //evaluates to 0 + 1 + 1 + 1
    #undef X
    

    This is also transparent to an IDE, so auto-completes will work fine (as its all done in the pre-processor).

    0 讨论(0)
提交回复
热议问题