Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 572
Cinolt Yuklair Avatar asked Sep 02 '16 12:09

Cinolt Yuklair


2 Answers

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

like image 143
cxw Avatar answered Nov 04 '22 07:11

cxw


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.

like image 4
user924037 Avatar answered Nov 04 '22 08:11

user924037