15

How to get enum count

I have a Enum

typedef enum{

DEL_TIME_VALUE    = -1,
DEL_TIMESEC_VALUE = 100,
DEL_TIMEMIN_VALUE = 200,
DEL_TIMEHOUR_VALUE = 300,
DEL_DAY_VALUE      = 1000,
DEL_COUNT_VALUE    = 1000,
....
.....
.....
DEL_END             =90002
}WORKINGTIME;

How do i get the enum count.

I try below for loop!

for(int i=DEL_TIME_VALUE; i<=DEL_END; i++) {

}

I guess its not good one!

can any one tell me how to get enum count! which are declared in enum.

Thanks in advance!

kiran
  • 4,285
  • 7
  • 53
  • 98
  • 1
    possible duplicate of [(How) can I count the items in an enum?](http://stackoverflow.com/questions/2102582/how-can-i-count-the-items-in-an-enum) – Luke Feb 05 '13 at 21:21

2 Answers2

39

You can't.

There is one technique that allows you to get the enum count. It looks like

typedef enum {
    value_one,
    value_two,
    value_three,
    ...
    enum_count
} my_enum;

Now the value enum_count is the count of values in the enum. However, this technique only works if the enums all carry their implicit value, where value_one is 0, value_two is 1, etc. Because of this, the last value in the enum always has the value of the count of enum values. In your case, your enum constants have explicit values that are not monotonically incrementing. There is no way to derive a count from this type of enum. And even in the theoretical world where you could derive a count, that wouldn't help you because you could not derive the value of a given enum constant.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 1
    This is a great technique that I've used a ton before too, just thought it worth adding that I've sometimes used it to extend an enum into a second one, in a subclass for example, and still ensuring unique values like this. typedef enumTwo{ secondTypeOfValueOne = enum_count + 1, secondTypeOfValueTwo, etc, secondTypeOfValueCount } – Jef Feb 21 '14 at 01:55
  • Brilliant solution :() – Asi Givati Sep 13 '16 at 13:13
2

The values of an enum are compile time constants, and are not available for introspection in your code.

Instead, you can look at implementing a custom enum class with Objective-C (something akin to the Java typesafe Enum http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html).

pgb
  • 24,813
  • 12
  • 83
  • 113