C – How to Count the Number of Elements in an Enum

c++enums

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.

Best Answer

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.

Related Question