Skip to content

Unused

stackoverflow How do I best silence a warning about unused variables?

A

You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.

E.g.

void foo(int param1, int param2)
{
    (void)param2;
    bar(param1);
}

Or,

#define UNUSED(expr) do { (void)(expr); } while (0)
...

void foo(int param1, int param2)
{
    UNUSED(param2);
    bar(param1);
}

Comment

I wonder how to do that for a variadic template. In template<typename... Args> void f(const Args&... args) I can't write (void)args; or (void)args...; because both are syntax errors. – panzi May 18 '14 at 16:27

@panzi : Use pack expansion, something like: (void) (0 + ... + (args, 0))Mark K Cowan Jan 16 '19 at 19:38

@MarkKCowan Or just ((void)args, ...). – L. F. Jul 8 '19 at 11:34

NOTE: 1、这是fold expression

A

In GCC and Clang you can use the __attribute__((unused)) preprocessor directive to achieve your goal. For example:

int foo (__attribute__((unused)) int bar) {
   return 0;
}

stackoverflow How do I best silence a warning about unused variables? # A

// silence a warning about unused variables,https://stackoverflow.com/a/1486931
#define UNUSED(expr) do { (void)(expr); } while (0)

Example: 在cppreference static_cast conversion4)就是说明的discard value expression,Example也对此进行了说明。

Variadic template

在 stackoverflow How do I best silence a warning about unused variables? # A 的comment中提及了这个topic,下面是完整的code:

template<typename ... Args>
void f(const Args &... args)
{
    ((void)args, ...);
}

int main()
{

}
// g++   --std=c++11 -Wall -pedantic -pthread main.cpp && ./a.out

编译输出如下:

main.cpp: In function 'void f(const Args& ...)':
main.cpp:4:15: warning: fold-expressions only available with '-std=c++17' or '-std=gnu++17'
    4 |  ((void)args, ...);

TODO

1、jmmv Unused parameters in C and C++

2、stackoverflow Unused parameter in c++11