【问题标题】:Storing inputs to a macro in an array (C)将输入存储到数组中的宏 (C)
【发布时间】:2017-09-13 13:43:45
【问题描述】:

我已经定义了如下所示的宏。

#define NAME_OUT(name_in)  PRE_##name_in##_POST

我想使用我在表/数组中定义的名称来遍历这个宏。有可能做这样的事情吗?如果是这样,我该怎么做?

注意:以上示例仅用于说明目的:)

【问题讨论】:

  • 迭代宏?你什么意思?无论如何,我非常怀疑你能做到。宏“名称”仅在预处理阶段之前存在。
  • boost preprocessor library 可以使用预处理器执行某些类型的迭代。它似乎不适合您直接执行的操作,但您可以更改使用该库的方法。我们确实需要在您的问题中提供更多详细信息,以便为您提供有用的信息。

标签: c arrays macros


【解决方案1】:

您的要求并不完全清楚,但听起来很像您在寻找“X 宏”模式:

#include <stdio.h>

// list of data
#define NAME_LIST \
  X(foo)          \
  X(bar)          \
  X(hello)        \
  X(world)


// whatever you are actually using these for, maybe an enum or variable names?
typedef enum  
{
  // temporarily define the meaning of "X" for all data in the list:
  #define X(name) PRE_##name##_POST,
    NAME_LIST
  #undef X // always undef when done
} whatever_t;


// helper macro to print the name of the enum    
#define STRINGIFY(str) #str


int main()
{
  #define X(name) printf("%s %d\n", STRINGIFY(PRE_##name##_POST), PRE_##name##_POST);
    NAME_LIST
  #undef X
}

输出:

PRE_foo_POST 0
PRE_bar_POST 1
PRE_hello_POST 2
PRE_world_POST 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多