How to make a variadic macro (variable number of arguments)

前端 未结 5 1418
遥遥无期
遥遥无期 2020-11-22 11:48

I want to write a macro in C that accepts any number of parameters, not a specific number

example:

#define macro( X )  something_complicated( whateve         


        
5条回答
  •  抹茶落季
    2020-11-22 12:30

    #define DEBUG
    
    #ifdef DEBUG
      #define PRINT print
    #else
      #define PRINT(...) ((void)0) //strip out PRINT instructions from code
    #endif 
    
    void print(const char *fmt, ...) {
    
        va_list args;
        va_start(args, fmt);
        vsprintf(str, fmt, args);
            va_end(args);
    
            printf("%s\n", str);
    
    }
    
    int main() {
       PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
       return 0;
    }
    

    If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:

    #define PRINT //
    

    or

    #define PRINT if(0)print
    

    The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);

提交回复
热议问题