Portable UNUSED parameter macro used on function signature for C and C++

Šimon Tóth picture Šimon Tóth · Aug 17, 2011 · Viewed 41.2k times · Source

I'm interested in creating a macro for eliminating the unused variable warning.

This question describes a way to suppress the unused parameter warning by writing a macro inside the function code:

Universally compiler independent way of implementing an UNUSED macro in C/C++

But I'm interested in a macro that can be used in the function signature:

void callback(int UNUSED(some_useless_stuff)) {}

This is what I dug out using Google (source)

#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#elif defined(__cplusplus)
# define UNUSED(x)
#else
# define UNUSED(x) x
#endif

Can this be further expanded for other compilers?

Edit: For those who can't understand how tagging works: I want a solution for both C and C++. That is why this question is tagged both C and C++ and that is why a C++ only solution is not acceptable.

Answer

Matt Clarkson picture Matt Clarkson · Sep 13, 2013

The way I do it is like this:

#define UNUSED(x) (void)(x)
void foo(const int i) {
    UNUSED(i);
}

I've not had a problem with that in Visual Studio, Intel, gcc and clang.

The other option is to just comment out the parameter:

void foo(const int /*i*/) {
  // When we need to use `i` we can just uncomment it.
}