C Preprocessor Remove Trailing Comma

做~自己de王妃 提交于 2020-01-22 17:24:07

问题


I have a macro like this:

#define C( a... ) ( char *[] ){ a, 0 }

This works for non-empty arguments:

C( "a", "b" ) => ( char *[] )( "a", "b", 0 }

But I want to remove the trailing comma when provided with an empty argument:

C() => ( char *[] ){ , 0 }

Is this possible?


回答1:


At least in GCC 5.4.0, on Cygwin (default -std=gnu11), this appears to do what you want (assuming I understand your question correctly):

#define C( a... ) ( char *[] ){ a 0 }
                                 ^ no comma!    
C( "a", "b", ) 
           ^ comma here
=> ( char *[] )( "a", "b", 0 }

C() 
=> ( char *[] ){ 0 }

Tested with gcc -E and no other command-line options.

Edit As @KerrekSB noted, this is not portable. The GCC preprocessor docs have this to say (emphasis added):

The above explanation is ambiguous about the case where the only macro parameter is a variable arguments parameter [as in this situation-Ed.], as it is meaningless to try to distinguish whether no argument at all is an empty argument or a missing argument. In this case the C99 standard is clear that the comma must remain, however the existing GCC extension used to swallow the comma. So CPP retains the comma when conforming to a specific C standard, and drops it otherwise.

So the above works fine in GCC, but might not on other compilers. However, it does work for me with gcc -std=c90 -E (or c99, or c11).




回答2:


Check out GCC's __VA_OPT__() function macro that can be used within a variadic macro.

#define C(...) (char *[]) { __VA_ARGS__ __VA_OPT__(,) 0 }

C("a", "b");   expands to (char *[]) { "a", "b" , 0 };
C();           expands to (char *[]) { 0 };

The arguments passed to __VA_OPT__() will only be expanded if __VA_ARGS__ is non-empty.



来源:https://stackoverflow.com/questions/39291976/c-preprocessor-remove-trailing-comma

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