c - token 粘贴前如何在宏参数中操作?

标签 c macros

我有一个函数 (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/

相关文章:

c - macOS 上的 "Return type of main is not int"警告

c - insertBefore 链表

c - 如何比较两个字符数组?

c - 数组下标的类型为 'char'

module - 在 Racket 中找到模块的名称?

c - 使用结构体指针访问结构体的指针成员

c++ - 使用#pragma once 有什么危险?

c++ - 从宏 block 中提取变量

macros - 我可以从 Vim 脚本函数中检测 Vim 宏录制模式,并在 Vim 宏录制模式下调用该函数吗?

c - 启用宏的语言如何跟踪源代码以进行调试?