C预处理程序删除结尾的逗号 [英] C Preprocessor Remove Trailing Comma

查看:87
本文介绍了C预处理程序删除结尾的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的宏:

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

这适用于非空参数:

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

但我想当提供空参数时,删除尾部逗号:

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

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

可能吗?

推荐答案

至少在Cygwin上的GCC 5.4.0中(默认 -std = gnu11 ),这似乎可以满足您的要求(假设我正确理解了您的问题):

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 }

gcc -E ,没有其他命令行选项。

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

编辑为@KerrekSB注意,这不是可移植的。 GCC预处理器文档可以这样说(强调):

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


上面的解释对于唯一的宏参数是可变参数参数 [如在这种情况下-Ed。] 的情况是模棱两可的,因为试图区分是否没有参数是空参数或缺少参数。在这种情况下,C99标准明确规定必须保留逗号,但是现有的GCC扩展用于吞下逗号。 因此,CPP在符合特定的C标准时会保留逗号,否则会删除逗号。

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.

上面的代码在GCC中工作正常,但在其他编译器上可能不行。但是,它对 gcc -std = c90 -E (或 c99 c11 )。

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

这篇关于C预处理程序删除结尾的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆