How to check how many elements an enum has?

While C language doesn't offer build in method to check how many elements an enum has, it's still possible to obtain this information by using a simple trick.

The idea is to add a dummy element at the very end, since numeric enums values are 0, 1, 2, 3, 4, 5, ..., the numeric value of last element will be also the amount of elements that this enum has.

#include <stdio.h>

typedef enum Fruit {
    /* place new elements below */
    /* guard */
} Fruit;

int main()
    int fruitEnumLength = (FRUIT_LAST_ELEMENT - 1);
    printf("Fruit enum has %d elments counting from zero.\n", fruitEnumLength);

    return 0;
sh-4.3$ gcc -o main *.c                                                                                                                                                                                                                                 
sh-4.3$ main                                                                                                                                                                                                                                            
Fruit enum has 2 elments counting from zero.  

This technique may be useful for sanitizing input data or for writing tests.

0 commentaires:

Post a Comment