C Preprocessor Remove Trailing Comma

前端 未结 2 603
一向
一向 2021-02-19 07:30

I have a macro like this:

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

This works for non-empty arguments:

C( \"a\", \"b\" ) => (          


        
相关标签:
2条回答
  • 2021-02-19 07:53

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

    0 讨论(0)
  • 2021-02-19 08:00

    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.

    0 讨论(0)
提交回复
热议问题