Thursday, April 28, 2011

Number of elements in an enum

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
};

But this only works if the items are sequential and start at zero.

From stackoverflow
  • Unfortunately, no. There is not.

  • 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;
    
    ojblass : can enum types be negative? If so watch out with this one.
    paxdiablo : FIRST=-2 would still calculate correctly, I think: 1 - (-2) = 3.
    Brian Campbell : No need to watch out; subtraction works just fine for negative numbers. Pax has it right.
    ojblass : FIRST = -200, SECOND = -199, THIRD = -198, END = -100. -200 - (-100) = bad news
    ojblass : One case that works does not a proof make.
    ojblass : even sequiental that breaks
    Brian Campbell : I meant sequential as in you only ever set the first value, and let each remaining value increment by default, in sequence. enum blah { FIRST= , SECOND, THIRD, END };
    ojblass : like i am saying thought setting the first to -9 and having 3 elements -9 - (-7) = -2. You need an absolute value or something.
    Brian Campbell : No, you would get FIRST = -9 SECOND = -8 THIRD = -7 END = -6, so you'd have -6 - (-9) = -6 + 9 = 3
    ojblass : ah yes... duh...
    Brian Campbell : No problem; an easy mistake to make.
  • 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?

    ojblass : Yes why would you want to do that!
  • See this SO question about enums in C++ like in Ada.

0 comments:

Post a Comment