Variadic UNUSED function/macro

后端 未结 4 1119
陌清茗
陌清茗 2021-02-04 11:25

A well-known and portable way to suppress C compiler warnings about unused variables is (see unused parameter warnings in C code):

#define UNUSED(x) (void)(x)
         


        
4条回答
  •  情书的邮戳
    2021-02-04 12:19

    What do you think about this:

    #define UNUSED(...) [__VA_ARGS__](){};
    

    Example:

    void f(int a, char* b, long d)
    {
        UNUSED(a, b, d);
    }
    

    Should be expanded ad a lambdas definition:

    [a,b,d](){}; //optimized by compiler (I hope!)
    

    ===== Tested with http://gcc.godbolt.org ===== I've tryed with this code:

    #define UNUSED(...) [__VA_ARGS__](){};
    
    int square(int num, float a) {
      UNUSED(a);
      return num * num;
    }
    

    The resulting output (compiled with -O0 -Wall) is:

    square(int, float):
        pushq   %rbp
        movq    %rsp, %rbp
        movl    %edi, -4(%rbp)
        movss   %xmm0, -8(%rbp)
        movl    -4(%rbp), %eax
        imull   -4(%rbp), %eax
        popq    %rbp
        ret
    

    EDIT:

    If you can use C++11 this could be a better solution :

    template 
    void UNUSED(Args&& ...args)
    {
        (void)(sizeof...(args));
    }
    

提交回复
热议问题