简体   繁体   中英

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

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?

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*))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM