3

I have 2 enum types:

typedef enum {a=0, a1=3, a2=5} NX;
typedef enum {c=-1, c1=4, c2=7} NY;

I'd like to write an expression, that given a name of enum type/instance would return me the value of its first element. A possible solution is to always add fixed-name elements like

typedef enum {a=0, first=a, a1, a2, last=a2}

but, maybe there is a more elegant way.

Is there a way to get number of elements in the enum in run-time?

tblum
  • 153
  • 6

2 Answers2

0

No, sizeof() does not work on enum's. It is not possible to get number of elements in runtime.
There is one popular approach to check enum's last element value to determine amount of elements in a given enum, i.e.:

enum Type {A = 0, B, C, LAST};
printf("'Type' enum has %d number of elements", LAST);
Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
0

If the numbers in the enum are sequential (and in your first two examples they are) you can always use

typedef enum {first = -18, b, c, d, last } BlahBlah;
(...)
int nptElements = last - first + 1;

to get the number of elements. This, of course, requires knowledge of the first and last...

rpsml
  • 1,486
  • 14
  • 21
  • Sure, but I don't want to rely on enum value names in the code. I wonder if there is a compiler built-in way, working on any enum. – tblum Aug 16 '12 at 10:10
  • Then, as far as I know, either you store the information you need in the enum itself (or in a series of #defines or variables) or you use an array, in which case you loose the labeling feature. – rpsml Aug 16 '12 at 10:18
  • You also have the c++ overkill in the stl::map container. – rpsml Aug 16 '12 at 10:26