JohnDoe
JohnDoe

Reputation: 915

How to define size of enum minus one element

if I have enum:

typedef enum
{
   A= 0,
   B= 1,
   C =2,
   D= 4,
   E= 6,
   F= 8,
   G= 10,

   MAX_ELEMENTS
}my_enum

How can I declare the number of elements within enum without one element?

something like this:

uint8 enum_numb_elements = MAX_ELEMENTS - 1

This is not a good practice to do arithmetic operation on enums. Is there an other way?

Upvotes: 0

Views: 182

Answers (2)

DiegoSunDevil
DiegoSunDevil

Reputation: 116

I prefer to keep enums contiguous to exploit the 'features' of C..

typedef enum
{
   A,
   B,
   C,
   D,
   E,
   F,
   G,
   MAX_ELEMENTS
} my_enum;

int element_array[MAX_ELEMENTS] =
{
    0,
    1,
    2,
    4,
    6,
    8,
    10
};

Given this construct, NUM_ELEMENTS adjusts automatically if you add/subtract enums, and you can use my_elem in for loops, etc. The major issue of concern is that you need to remember to maintain element_array in conjunction with my_enum when you add or remove enums.

A for loop example

my_elem elem;
for (elem = (my_elem)0; elem < MAX_ELEMENTS; elem++)
{
    printf("The value of element %d is %d\n", elem, element_array[elem] );
}

Upvotes: 0

You can define it, sort of, but it involves some boiler-plate that isn't all too pleasant, and pollutes the global/tag namespace a lot/bit.

If you leverage the notorious X macros for the job, it would look like this:

#define LIST_OF_ENUM_IDS \
    X(A, 0) \
    X(B, 1) \
    X(C, 2) \
    X(D, 4) \
    X(E, 6) \
    X(F, 8) \
    X(G, 10)

#define X(id, val) \
  id = val,

typedef enum
{
  LIST_OF_ENUM_IDS
} my_enum;

#undef X

#define X(id, val) id##_impl_helper,

enum my_enum_impl_helper__ {
  LIST_OF_ENUM_IDS
  MY_ENUM_MAX_ELEMENTS
};

#undef X

Live example: On Ideone


Alternatively, some shops will instead rely on bold comments and code reviews to catch such things:

/********************************************
*
**
*** ATTENTION! Remember to bump MAX_ELEMENTS
*** should you add new values to the enum
**
*
********************************************/
typedef enum
{
   A= 0,
   B= 1,
   C =2,
   D= 4,
   E= 6,
   F= 8,
   G= 10,

   MAX_ELEMENTS = 7 /// Bump this if you add new values!
}my_enum;

Which can work not all too bad, despite the human factor.

Upvotes: 4

Related Questions