Cinolt Yuklair Cinolt Yuklair - 1 month ago 14x
C Question

C Preprocessor Remove Trailing Comma

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?

cxw cxw

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 }

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