This question comes up as one of the top 3 hits for the Google search for "how to suppress -Wunused-result in c++", so I'm adding this answer here since I figured it out and want to help the next person.
-Wunused
(or one of its sub-errors) or -Wunused -Werror
only, the solution is to cast to void
:For -Wunused
or one of its sub-errors only1, you can just cast it to void
to disable the warning. This should work for any compiler and any IDE for both C and C++.
1Note 1: see gcc documentation here, for example, for a list of these warnings: https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html, then search for the phrase "All the above -Wunused options combined" and look there for the main -Wunused
warning and above it for its sub-warnings. The sub-warnings that -Wunused
contains include:
-Wunused-but-set-parameter
-Wunused-but-set-variable
-Wunused-function
-Wunused-label
-Wunused-local-typedefs
-Wunused-parameter
-Wno-unused-result
-Wunused-variable
-Wunused-const-variable
-Wunused-const-variable=n
-Wunused-value
-Wunused
= contains all of the above -Wunused
options combinedExample of casting to void
to suppress this warning:
// some "unused" variable you want to keep around
int some_var = 7;
// turn off `-Wunused` compiler warning for this one variable
// by casting it to void
(void)some_var; // <===== SOLUTION! ======
For C++, this also works on functions which return a variable marked with [[nodiscard]]
:
C++ attribute: nodiscard (since C++17)
If a function declared nodiscard or a function returning an enumeration or class declared nodiscard by value is called from a discarded-value expression other than a cast to void, the compiler is encouraged to issue a warning.
(Source: https://en.cppreference.com/w/cpp/language/attributes/nodiscard)
So, the solution is to cast the function call to void
, as this is actually casting the value returned by the function (which is marked with the [[nodiscard]]
attribute) to void
.
Example:
// Some class or struct marked with the C++ `[[nodiscard]]` attribute
class [[nodiscard]] MyNodiscardClass
{
public:
// fill in class details here
private:
// fill in class details here
};
// Some function which returns a variable previously marked with
// with the C++ `[[nodiscard]]` attribute
MyNodiscardClass MyFunc()
{
MyNodiscardClass myNodiscardClass;
return myNodiscardClass;
}
int main(int argc, char *argv[])
{
// THE COMPILER WILL COMPLAIN ABOUT THIS FUNCTION CALL
// IF YOU HAVE `-Wunused` turned on, since you are
// discarding a "nodiscard" return type by calling this
// function and not using its returned value!
MyFunc();
// This is ok, however, as casing the returned value to
// `void` suppresses this `-Wunused` warning!
(void)MyFunc(); // <===== SOLUTION! ======
}
Lastly, you can also use the C++17 [[maybe_unused]]
attribute: https://en.cppreference.com/w/cpp/language/attributes/maybe_unused.