[英]How to get value macro in C?
I'm having trouble with macros in C. Is there any way to call and get the value of a parameter in macro to call a function?我在使用 C 中的宏时遇到了问题。有没有办法在宏中调用并获取参数的值来调用函数?
The example code below generates an error:下面的示例代码生成错误:
#define order(i) fruits_i##_banana()
void fruits_1_banana()
{
printf("Order banana\n");
}
int main()
{
int a = 1;
order(a);
}
You need to use ##
before and after i
.您需要在
i
之前和之后使用##
。
#define order( i ) fruits_##i##_banana()
void fruits_1_banana()
{
printf("Order banana\n");
}
int main()
{
order(1);
}
Note that you cannot pass a
to order
because macro expansion doesn't take the value of a variable, it just uses the variable name as it is.请注意,您不能将
a
传递给order
因为宏扩展不采用变量的值,它只是按原样使用变量名称。
References: https://docs.microsoft.com/en-us/cpp/preprocessor/token-pasting-operator-hash-hash?view=msvc-160参考资料: https : //docs.microsoft.com/en-us/cpp/preprocessor/token-pasting-operator-hash-hash?view=msvc-160
Instead, you can use an array of function pointers:相反,您可以使用函数指针数组:
#include <stdio.h>
static void fruits_0_banana(void)
{
printf("Order banana 0\n");
}
static void fruits_1_banana(void)
{
printf("Order banana 1\n");
}
static void (*order[])(void) = {
fruits_0_banana, // Or NULL if you don't need it
fruits_1_banana,
// ...
};
int main(void)
{
int a = 1;
order[a]();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.