What is the best way to suppress A "Unused variable x" warning? [duplicate]

What is the best/neatest way to suppress a compiler (in this case GCC) like "Unused variable x" warning?

I don't want to give any certain flags to GCC to remove all these warnings, just for special cases.


(void) variable might work for some compilers.

For C++ code, also see Mailbag: Shutting up compiler warnings where Herb Sutter recommends using:

template<class T> void ignore( const T& ) { }

...

ignore(variable);

Do not give the variable a name (C++)

void foo(int /*bar*/) {
    ...
}

Tell your compiler using a compiler specific nonstandard mechanism

See individual answers for __attribute__((unused)), various #pragmas and so on. Optionally, wrap a preprocesor macro around it for portability.

Switch the warning off

IDEs can signal unused variables visually (different color, or underline). Having that, compiler warning may be rather useless.

In GCC and Clang, add -Wno-unused-parameter option at the end of the command line (after all options that switch unused parameter warning on, like -Wall, -Wextra).

Add a cast to void

void foo(int bar) {
    (void)bar;
}

As per jamesdlin's answer and Mailbag: Shutting up compiler warnings.


I found an article, http://sourcefrog.net/weblog/software/languages/C/unused.html, that explains UNUSED. It is interesting that the author also mangles the unused variable name, so you can't inadvertently use it in the future.

Excerpt:

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

void dcc_mon_siginfo_handler(int UNUSED(whatsig))