C Preprocessor Remove Trailing Comma

前端 未结 2 595
一向
一向 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).

提交回复
热议问题