Peter Gibson Peter Gibson - 4 months ago 8
C Question

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.

Answer

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;