【问题标题】:Auto-incrementing macro expansion自增宏扩展
【发布时间】:2012-04-02 15:42:13
【问题描述】:

使用普通的 C 预处理器宏,是否可以创建如下内容:

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

【问题讨论】:

  • 为什么需要一个预处理器#define?为什么不只是一个枚举?

标签: c macros c-preprocessor


【解决方案1】:

宏不能自动进行这种类型的计数,但enums 可以。

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

除非您真的想要使用宏,否则您将不得不手动进行计数:

#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

【讨论】:

  • ...并且您想在 INIT_BASE + N 表达式周围加上括号。
  • 漂亮!!我错误地假设枚举在运行时会占用内存。
【解决方案2】:

你试过了吗:

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

?

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2020-10-18
    • 2014-02-24
    相关资源
    最近更新 更多