Is there any way to suppress "unused variable" warnings for a specific file, namespace, or specific variable?
I ask because I have a namespace containing a big list of lambda functions. Some are not used now, but might be used in time. If these were regular free functions, I would not be warned if some were unused. However, because they are lambdas, I end up with a stack of compiler warnings.
I do not want to use a compiler flag to remove all of this type of warning, as normally, it is very useful to have the compiler catch unused variables. However, a stack of warnings about unused utility functions adds noise to otherwise useful information.
There are two approaches that come to mind. First of all, most build environments enable per-source compiler flags, so you should be able to turn off that warning just for the single file where all those lambdas are defined.
Then there is a general approach to silence such warnings for single variables: use it, but not really do anything with it. On some compilers this can be achieved with a simple cast to void:
auto x = /* ... */;
(void) x;
But more effective is defining a simple function that makes it look (for the compiler) as if the variable was used:
template <class T>
void ignore_unused(T&) {}
//later...
auto x = /* ... */;
ignore_unused(x);
Note the parameter has no name, so the compiler will not complain about that one to be unused.
The idea is pretty common: do something with the variable that effectively makes no operation but silences the static analyzer that emits the "unused variable" warning.
Boost has a similar function, boost::ignore_unused_variable_warning()
For more information, see Herb Sutter's blog.
In C++ you can static_cast
anything to void
.
What is the use of such a cast if it does not produce any side effects or a value one might ask?
Precisely to tell the compiler that an object is "used" in a portable way.
So,
auto x = /*...*/;
static_cast<void>(x);
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