[英]How to pass a macro as an argument in a C function?
I want to pass a macro as an argument in a C function, and I don't know if it possible.我想在C函数中传递一个宏作为参数,不知道是否可以。 I would like to see this operation, for instance:
我想看看这个操作,例如:
I have these macros:我有这些宏:
#define PRODUCT(A, B) ((A) * (B))
#define SUM(A, B) ((A) + (B))
And then I have this function with the following signature:然后我有这个带有以下签名的函数:
int just_a_function(int x, MACRO_AS_PARAMATER_HERE);
and then i want to call this function like:然后我想像这样调用这个函数:
just_a_function(10, SUM);
is it possible?是否可以?
Thanks谢谢
You can't pass as function argument.您不能作为函数参数传递。
But if function is a macro this is possible.但是如果函数是一个宏,这是可能的。
#include <stdio.h>
#define PRODUCT(A, B) ((A) * (B))
#define SUM(A, B) ((A) + (B))
#define JUST_A_FUNCTION(A, B, MACRO) MACRO(A, B)
int main() {
int value;
value = JUST_A_FUNCTION(10, 10, SUM);
printf("%d\n", value);
value = JUST_A_FUNCTION(10, 10, PRODUCT);
printf("%d\n", value);
return 0;
}
You can't do that.你不能那样做。
Use normal functions instead:改用普通函数:
int sum(int x, int y)
{
return x+y;
}
//...
just_another_function(10, sum);
Note: just_another_function
must accept int (*)(int, int)
as the second argument.注意:
just_another_function
必须接受int (*)(int, int)
作为第二个参数。
typedef int (*TwoArgsFunction)(int, int);
int just_another_function(int x, TwoArgsFunction fun);
Hi what you are passing is macro means its a substitution your passing .嗨,您传递的是宏,这意味着它是您传递的替代品。 Think about it .. Ex : #define HIGH 1 In a function you can use int variable.
想想看.. 例如:#define HIGH 1 在一个函数中,你可以使用 int 变量。 So you can pass 1 to the function .
所以你可以将 1 传递给函数。 In a function its stored as integer variable
在函数中,它存储为整数变量
Preprocessor directive works first .预处理器指令首先起作用。 Once in a main macro are replaced means in the sense in a function you have to take care of the substitution.
一旦在主宏中被替换意味着在函数中你必须处理替换。 If I would have used Macro High 1 ,, in function I will take as int as a argument to get for local function stack.
如果我使用 Macro High 1 , 在函数中我将把 int 作为参数来获取本地函数堆栈。 For better understanding check the topics 1.preprocessor directive 2. How the hex file created once you will compile
为了更好地理解,请查看主题 1.preprocessor 指令 2. 编译后如何创建 hex 文件
#include <stdio.h>
#define HIGH 1
#define LOW 0
void pin(int, int);
void pin(int a, int b) {
printf("A: %d B: %d\n", a, b);
}
int main() {
pin(1, HIGH);
return 0;
}
Compilation step involve:编译步骤包括:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.