Recursive C macro not expanded

和自甴很熟 提交于 2021-02-16 21:25:13

问题


I am working on a recursive macro. However, it seems that it is not expanded recursively. Here is a minimal working example to show what I mean:

// 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)

The recursive macro should expand itself recursively and always concatenate the result, separated with a colon. However, it doesn't work. The recursive macro is generated correctly (as can be seen on the result a:recursive(b,c,d) which includes a well-formed call to the macro again), but the generated recursive call ist not exanded.

Why is this the case and how can I get the behaviour I want?


回答1:


You can't get the behaviour you want. The C preprocessor is, by design, not turing complete.

You can use multiple macros to get multiple replacements, but you will not achieve true recursion with an arbitrary number of replacements.




回答2:


As others have mentioned, pure recursion is impossible with C macros. It is, however, possible to simulate recursion-like effects.

The Boost Pre-Processor tools do this well for both C and C++ and are a stand-alone library:

http://www.boost.org/doc/libs/1_60_0/libs/preprocessor/doc/index.html




回答3:


The compiler pre-processor will not re expand the macro that you define. That is it will blindly replace whatever string is found in the macro statement with the string that it finds in the definition. For example, Can we have recursive macros? or Macro recursive expansion to a sequence and C preprocessor, recursive macros

That is, recursive(a,b,c,d) will be expanded to a:recursive(b,c,d) and the pre-processor will then continue to the next line in the base code. It will not loop around to try to continue to expand the string (see the links that I cited).



来源:https://stackoverflow.com/questions/36481223/recursive-c-macro-not-expanded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!