如何在C预处理器的#define中使用#if? [英] How to use #if inside #define in the C preprocessor?

查看:122
本文介绍了如何在C预处理器的#define中使用#if?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个宏,该宏根据其参数的布尔值吐出代码。因此,说 DEF_CONST(true)应该扩展为 const DEF_CONST(false)应该扩展为空。

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 DEF_CONST(false) should be expanded into nothing.

很显然,以下操作无效,因为我们无法在#defines中使用另一个预处理器:

Clearly the following doesn't work because we can't use another preprocessor inside #defines:

#define DEF_CONST(b_const) \
#if (b_const) \
  const \
#endif


推荐答案

您可以使用宏令牌串联如下:

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

然后,

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

用于将宏参数传递给DEF_CONST本身(如GMan和其他人正确指出的那样):

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

这篇关于如何在C预处理器的#define中使用#if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆