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)
I'm looking for a way to generalize this to take multiple inputs (of different type):
void foo(int a, long b, void* c){
/* Want this: */
ALL_UNUSED(a, b, c);
/* instead of: */
UNUSED(a);
UNUSED(b);
UNUSED(c);
}
One way that seems to do the trick is to use a variadic function
static inline void ALL_UNUSED(int dummy, ...) {}
However, I suspect this solution is objectionable in the expert eye.
Is there a standard-compliant and portable (i.e. not using __attribute__((unused))
) way to make a variadic UNUSED() function/macro? Many thanks!
EDIT
There does not seem to exist a clean way of doing what I asked for in the context of C99 or the C preprocessor. Such is life.
In his answer below, @Dabo shows a pretty interesting way of doing what I asked for using a series of macros. This is neat and informative (at least to me), so I accept that answer. That said, I would not deploy it in a big project because it's tearse enough to outweigh the benefit it brings (in my eyes). But people will come to different conclusions here.
As noted below, the approach of using an empty variadic function is not perfect either. While it's a pretty elegant one-liner, it will provoke warnings about unititialized variables (if they are). Also, you have to trust your compiler to completely optimize it away, which I object to in principle but that all compilers I have tried with actually do.
One relevant case is when stubbing functions after an early high-level interface design phase. Then your unused variables will all be function arguments and initialized by definition, and the following approach works fine
static inline void UNUSED(int dummy, ...) {}
void foo(int a, long b, void* c){
UNUSED(a, b, b); /* No warnings */
}
I took Dabo's (https://stackoverflow.com/a/23238813/5126486) awesome solution and improved a little bit so it's easier to extend to more than 5:
#define UNUSED0()
#define UNUSED1(a) (void)(a)
#define UNUSED2(a,b) (void)(a),UNUSED1(b)
#define UNUSED3(a,b,c) (void)(a),UNUSED2(b,c)
#define UNUSED4(a,b,c,d) (void)(a),UNUSED3(b,c,d)
#define UNUSED5(a,b,c,d,e) (void)(a),UNUSED4(b,c,d,e)
#define VA_NUM_ARGS_IMPL(_0,_1,_2,_3,_4,_5, N,...) N
#define VA_NUM_ARGS(...) VA_NUM_ARGS_IMPL(100, ##__VA_ARGS__, 5, 4, 3, 2, 1, 0 )
#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__ )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With