The usual purpose of casting to void
is to “use” the result of a computation. In relatively strict build environments it is common to output warnings, or even errors, when a variable is declared, maybe even written to, but the result is never used. If, in your code, you know you do not need a result somewhere, you can use the static_cast<void>
method to mark the result as discarded – but the compiler will consider the variable used then and no longer create a warning or error.
An example:
#include <iostream>
int myFunction() __attribute__ ((warn_unused_result));
int myFunction()
{
return 42;
}
int main()
{
// warning: ignoring return value of 'int myFunction()',
// declared with attribute warn_unused_result [-Wunused-result]
myFunction();
// warning: unused variable 'result' [-Wunused-variable]
auto result = myFunction();
// no warning
auto result2 = myFunction();
static_cast<void>(result2);
}
When compiled with g++ -std=c++14 -Wall example.cpp
, the first two function calls will create warnings.
As VTT pointed out in his post, from C++17 you have the option of using the [[maybe_unused]]
attribute instead.