Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intentionally discard a [[nodiscard]] return value?

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"?

like image 465
spraff Avatar asked Dec 02 '18 15:12

spraff


People also ask

What is[[ nodiscard]] in c++?

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.

Should I use [[ Nodiscard ]]?

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.


1 Answers

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."

like image 53
Hatted Rooster Avatar answered Oct 08 '22 03:10

Hatted Rooster