如何通过将标记粘贴在一起来创建类似函数的宏标记

How to create a function-like macro token by pasting tokens together

我有一组预定义的宏(我无法更改),其中每个宏都将数组的索引作为输入。我想创建另一个宏,以便能够通过将标记粘贴在一起来选择要使用的先前定义的宏。

我已经尝试创建一个接受 2 个参数的宏:x,它选择要使用的先前定义的宏,以及 ind,它被传递给选定的宏。

下面的代码 运行 使用 https://www.onlinegdb.com/online_c_compiler 这样我就可以在将它放入一个相当大的应用程序之前找出基本代码。

#include <stdio.h>

//struct creation
struct mystruct {
    int x;
    int y;
};

//create array of structs
struct mystruct sArr1[2] = {{1,2},{3,4}};
struct mystruct sArr2[2] = {{5,6},{7,8}};

//define macros
#define MAC1(ind) (sArr1[ind].x)
#define MAC2(ind) (sArr2[ind].y)

// Cannot change anything above this //

//my attempt at 2 input macro
#define MYARR(x,ind) MAC ## x ## (ind)

int main() {
    printf("%d\n", MYARR(1, 0));
    return 0;
}

我希望结果在索引 0 处打印出 sArr1x 值,即 1。相反,我得到了这个输出

main.c: In function ‘main’:
main.c:29:22: error: pasting "MAC1" and "(" does not give a valid preprocessing token
 #define MYARR(x,ind) MAC ## x ## (ind)
                      ^
main.c:33:19: note: in expansion of macro ‘MYARR’
     printf("%d\n", MYARR(1, 0));

第 29 行应该是:

#define MYARR(x,ind) MAC##x(ind)

我测试过了。它打印了'1',这就是你想要的。