Say I have
[[nodiscard]] int foo () { return 0; } int main () { foo (); }
then
error: ignoring return value of ‘int foo()’, declared with attribute nodiscard [-Werror=unused-result]
but if
int x = foo ();
then
error: unused variable ‘x’ [-Werror=unused-variable]
Is there a clean way of telling the compiler "I want to discard this [[nodiscard]]
value"?
C++ Attributes [[nodiscard]]The [[nodiscard]] attribute can be used to indicate that the return value of a function shouldn't be ignored when you do a function call. If the return value is ignored, the compiler should give a warning on this. The attribute can be added to: A function definition.
It is never necessary to add the [[nodiscard]] attribute. From cppreference: 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.
Cast it to void
:
[[nodiscard]] int foo () { return 0; } int main () { static_cast<void>(foo()); }
This basically tells the compiler "Yes I know I'm discarding this, yes I'm sure of it."
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