我有一个函数 (ansi c) 在其定义中是递归的。因此,它的形式是:
void function_2(int *value){
/*this is the base function*/
}
void function_4(int *value){
function_2(value);
function_2(value);
/*other operations*/
}
void function_8(int *value){
function_4(value);
function_4(value);
/*other operations*/
}
等等。 为了创建这些函数,我正在创建宏,例如:
#define FUNCTION( m, h)\
void function_##m(int *value){\
function_##h(value);\
function_##h(value);\
/*other operations\
};
然后我做出如下声明:
FUNCTION(4,2)
FUNCTION(8,4)
请注意,第二个宏参数 (h) 始终是第一个宏参数 (m) 值的一半。有什么方法可以让我只使用一个参数 (m) 来制作宏,而不是对其进行操作,这样当我连接它时(使用 ##)我可以使用“m/2”而不是 h?
它应该是这样的:
function_##m/2(value);\
最佳答案
你不能像你想做的那样使用编译时计算和标记粘贴。另一方面,如果您 /*other operations*/
是相同的并且只有 m
的值在变化,那么最好使 m
到参数中,而不是使用宏来定义许多函数。
你可以使它类似于以下内容:
void function(int m, int *value) {
if ( m == 2 ) {
/*run base code*/
} else {
function(m/2, value);
function(m/2, value);
/*other operations*/
}
}
关于c - token 粘贴前如何在宏参数中操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968217/