Number of elements in an enum

后端 未结 8 2296
抹茶落季
抹茶落季 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:20

    I know this is a very old question, but as the accepted answer is wrong, I feel compelled to post my own. I'll reuse the accepted answer's example, slightly modified. (Making the assumption that enums are sequential.)

    // Incorrect code, do not use!
    enum blah {
      FIRST   =  0,
      SECOND, // 1
      THIRD,  // 2
      END     // 3
    };
    const int blah_count = END - FIRST;
    // And this above would be 3 - 0 = 3, although there actually are 4 items.
    

    Any developer knows the reason: count = last - first + 1. And this works with any combination of signs (both ends negative, both positive, or only first end negative). You can try.

    // Now, the correct version.
    enum blah {
      FIRST   =  0,
      SECOND, // 1
      THIRD,  // 2
      END     // 3
    };
    const int blah_count = END - FIRST + 1; // 4
    

    Edit: reading the text again, I got a doubt. Is that END meant not to be part of the offered items? That looks weird to me, but well, I guess it could make sense...

    0 讨论(0)
  • 2020-12-05 02:22

    Unfortunately, no. There is not.

    0 讨论(0)
  • 2020-12-05 02:28

    Well, since enums can't change at run-time, the best thing you can do is:

    enum blah {
        FIRST = 7,
        SECOND = 15,
        THIRD = 9,
        LAST = 12
    };
    #define blahcount 4 /* counted manually, keep these in sync */
    

    But I find it difficult to envisage a situation where that information would come in handy. What exactly are you trying to do?

    0 讨论(0)
  • 2020-12-05 02:33

    I don't believe there is. But what would you do with such a number if they are not sequential, and you don't already have a list of them somewhere? And if they are sequential but start at a different number, you could always do:

    enum blah {
        FIRST = 128,
        SECOND,
        THIRD,
        END
    };
    const int blah_count = END - FIRST;
    
    0 讨论(0)
  • 2020-12-05 02:34

    If you don't assign your enums you can do somethings like this:

    enum MyType {
      Type1,
      Type2,
      Type3,
      NumberOfTypes
    }
    

    NumberOfTypes will evaluate to 3 which is the number of real types.

    0 讨论(0)
  • 2020-12-05 02:34
    int enaumVals[] =
    {
    FIRST,
    SECOND,
    THIRD,
    LAST
    };
    
    #define NUM_ENUMS sizeof(enaumVals) / sizeof ( int );
    
    0 讨论(0)
提交回复
热议问题