我正在研究递归宏。不过貌似不是递归展开的。这是一个最小的工作示例来说明我的意思:
// ignore input, do nothing
#define ignore(...)
// choose between 6 names, depending on arity
#define choose(_1,_2,_3,_4,_5,_6,NAME,...) NAME
// if more than one parameter is given to this macro, then execute f, otherwise ignore
#define ifMore(f,...) choose(__VA_ARGS__,f,f,f,f,f,ignore)(__VA_ARGS__)
// call recursively if there are more parameters
#define recursive(first,args...) first:ifMore(recursive,args)
recursive(a,b,c,d)
// should print: a:b:c:d
// prints: a:recursive(b,c,d)
recursive
宏应该递归地扩展自身,并始终连接结果,用冒号分隔。但是,它不起作用。递归宏已正确生成(如结果 a:recursive(b,c,d)
所示,其中再次包含对宏的格式正确的调用),但生成的递归调用列表未扩展。
为什么会这样,我怎样才能得到我想要的行为?
最佳答案
你得不到你想要的行为。 C 预处理器在设计上不是图灵完备的。
您可以使用多个宏来获得多个替换,但您无法通过任意数量的替换实现真正的递归。
关于c - 递归 C 宏未展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481223/