cmacrosc-preprocessor

Auto-incrementing macro expansion


With using plain C preprocessor macros, is it possible to create something like:

INIT_BASE(0x100)                     // init starting number

#define BASE_A  GET_NEXT_BASE         // equivalent to #define BASE_A 0x101
#define BASE_B  GET_NEXT_BASE         // 0x102
#define BASE_C  GET_NEXT_BASE         // 0x103

Solution

  • Macros can't do that type of counting automatically, but enums can.

    #define INIT_BASE 0x100
    enum foo
    {
        BASE_A = INIT_BASE + 1,
        BASE_B,
        BASE_C,
        ...
    };
    

    Unless you really want to use macros, you are going to have to do the counting manually:

    #define INIT_BASE  0x100
    #define BASE_A    (INIT_BASE + 1)    // equivalent to #define BASE_A 0x101
    #define BASE_B    (INIT_BASE + 2)    // 0x102
    #define BASE_C    (INIT_BASE + 3)    // 0x103