Counting preprocessor macros

后端 未结 5 1984
离开以前
离开以前 2021-01-02 03:46

I have this macro code, which allows me to define both a C enum and a list of the enumerated names as strings using one construct. It prevents me from havi

5条回答
  •  礼貌的吻别
    2021-01-02 04:16

    The following should work:

    #define ITEM_STRING_DEFINE(id, name) #name, // note trailing comma
    const char *itemNames[] = {
      ENUM_DEFINITIONS(ITEM_STRING_DEFINE)
    };
    
    #define TOTAL_ITEMS (sizeof itemNames / sizeof itemNames[0])
    

    Edit: Thank you to Raymond Chen for noting we don't have to worry about the unnecessary final comma in the list. (I had been misremenbering the problem for enums with strict C89 compilers, as in Is the last comma in C enum required?.)

提交回复
热议问题