How to use #if inside #define in the C preprocessor?

后端 未结 2 421
小鲜肉
小鲜肉 2020-11-27 20:13

I want to write a macro that spits out code based on the boolean value of its parameter. So say DEF_CONST(true) should be expanded into const, and

2条回答
  •  长情又很酷
    2020-11-27 20:47

    You can simulate conditionals using macro token concatenation as follows:

    #define DEF_CONST(b_const) DEF_CONST_##b_const
    #define DEF_CONST_true const
    #define DEF_CONST_false
    

    Then,

    /* OK */
    DEF_CONST(true)  int x;  /* expands to const int x */
    DEF_CONST(false) int y;  /* expands to int y */
    
    /* NOT OK */
    bool bSomeBool = true;       // technically not C :)
    DEF_CONST(bSomeBool) int z;  /* error: preprocessor does not know the value
                                    of bSomeBool */
    

    Also, allowing for passing macro parameters to DEF_CONST itself (as correctly pointed out by GMan and others):

    #define DEF_CONST2(b_const) DEF_CONST_##b_const
    #define DEF_CONST(b_const) DEF_CONST2(b_const)
    #define DEF_CONST_true const
    #define DEF_CONST_false
    
    #define b true
    #define c false
    
    /* OK */
    DEF_CONST(b) int x;     /* expands to const int x */
    DEF_CONST(c) int y;     /* expands to int y */
    DEF_CONST(true) int z;  /* expands to const int z */
    

    You may also consider the much simpler (though potentially less flexible):

    #if b_const
    # define DEF_CONST const
    #else /*b_const*/
    # define DEF_CONST
    #endif /*b_const*/
    

提交回复
热议问题