Home > database >  How to find out number of entries in initializer-list at compile-time?
How to find out number of entries in initializer-list at compile-time?

Time:01-27

I have the following code:

#define DEF1 "first"
#define DEF2 "second"
#define INIT_LIST { DEF1, DEF2 }

Is there any way to get number of entries in INIT_LIST at compile time?

CodePudding user response:

You can pass a char-pointer array of unknown size and initialized using INIT_LIST as a compound literal to sizeof. Then divide by sizeof char-pointer and you get the number of elements in INIT_LIST.

Like

#define INIT_LIST_ELEMENTS (sizeof((char*[])INIT_LIST) / sizeof(char*))
  • Related