Variadic UNUSED function/macro

后端 未结 4 1120
陌清茗
陌清茗 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:01

    Based on these two posts Variadic macro to count number of arguments, and Overloading macros i made the following

    #define UNUSED1(x) (void)(x)
    #define UNUSED2(x,y) (void)(x),(void)(y)
    #define UNUSED3(x,y,z) (void)(x),(void)(y),(void)(z)
    #define UNUSED4(a,x,y,z) (void)(a),(void)(x),(void)(y),(void)(z)
    #define UNUSED5(a,b,x,y,z) (void)(a),(void)(b),(void)(x),(void)(y),(void)(z)
    
    #define VA_NUM_ARGS_IMPL(_1,_2,_3,_4,_5, N,...) N
    #define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)
    
    #define ALL_UNUSED_IMPL_(nargs) UNUSED ## nargs
    #define ALL_UNUSED_IMPL(nargs) ALL_UNUSED_IMPL_(nargs)
    #define ALL_UNUSED(...) ALL_UNUSED_IMPL( VA_NUM_ARGS(__VA_ARGS__))(__VA_ARGS__ )
    

    what can be used as follows

     int main()
     {
        int a,b,c;
        long f,d;
    
        ALL_UNUSED(a,b,c,f,d);
    
        return 0;
      }
    

    eclipse macro expansion gives :

      (void)(a),(void)(b),(void)(c),(void)(f),(void)(d)
    

    compiled with gcc -Wall with no warnings

    EDIT:

    #define UNUSED1(z) (void)(z)
    #define UNUSED2(y,z) UNUSED1(y),UNUSED1(z)
    #define UNUSED3(x,y,z) UNUSED1(x),UNUSED2(y,z)
    #define UNUSED4(b,x,y,z) UNUSED2(b,x),UNUSED2(y,z)
    #define UNUSED5(a,b,x,y,z) UNUSED2(a,b),UNUSED3(x,y,z)
    

    EDIT2

    As for inline method you posted, a quick test

    int a=0;
    long f,d;
    
    ALL_UNUSEDINLINE(a,f,&d);
    

    gives ‘f’ is used uninitialized in this function [-Wuninitialized] warning. So here at least one use case which breaks generality of this aproach

提交回复
热议问题