c++ – Unused variables


Good day!

Can you please tell me, I'm reading Herb Sutter's book, and he writes the following code:

int a = 10;
a; //для подавления предупреждения о неиспользуемой переменной

The question is: why suppress this warning? Does this affect anything?


Unfortunately, the information in this book is clearly out of date. Suppressing a warning about an unused variable (or parameter) by writing an expression where there is nothing other than this variable will result in warnings in a useless expression .

To suppress the warning, you should have used casting a variable to void : static_cast<void>(a); (usually turns into a macro of UNUSED_VAR type). In this case, no warnings will follow .

In modern C ++, there is a way to mark a variable as specially unused. For this purpose, the standard maybe_unused attribute is maybe_unused : [[maybe_unused]] int a = 10; … And in this case, there will be no warnings .

It makes sense to suppress this warning only in one case, when there is a function whose result cannot be ignored, but we intentionally want to do this:

[[nodiscard]] int foo(void){ return 0; }

int main()
   foo(); // warning: result of foo is not used
   int a = foo(); // warning: unused variable a
   [[maybe_unsed]] int a = foo(); // no warnings
Scroll to Top