4

static_cast<void>() is the 'C++ way' of writing void conversion

In the en.cppreference.com website mentioned as discards the value of the expression. In below link four points on Explanation section

http://en.cppreference.com/w/cpp/language/static_cast

Where and Why should we use static_cast<void>()? give a example..

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Ledison Gomas
  • 43
  • 2
  • 8

2 Answers2

13

This is a way to tell that it is ok for a variable to be unused suppressing corresponding compiler warning. This approach has been deprecated with introduction of [[maybe_unused]] attribute in C++17.

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • @TheVee No, it is ok for variable to be used: from **[dcl.attr.unused]** *3 [Note: For an entity marked maybe_unused, implementations should not emit a warning that the entity is unused, or that the entity is used despite the presence of the attribute. —end note ]* – user7860670 Mar 14 '18 at 09:07
  • Unfortunately, the cast to void is still necessary for statements, to suppress warnings about unused expression results. – 303 Nov 11 '22 at 23:22
4

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.

mindriot
  • 5,413
  • 1
  • 25
  • 34