Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 365
Šimon Tóth Avatar asked Aug 17 '11 10:08

Šimon Tóth


2 Answers

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.
}
like image 173
Matt Clarkson Avatar answered Oct 22 '22 15:10

Matt Clarkson


Just one small thing, better using __attribute__((__unused__)) as __attribute__((unused)), because unused could be somewhere defined as macro, personally I had a few issues with this situation.

But the trick I'm using is, which I found more readable is:

#define UNUSED(x) (void)x;

It works however only for the variables, and arguments of the methods, but not for the function itself.

like image 11
doc_ds Avatar answered Oct 22 '22 16:10

doc_ds