1

I just ran across this in some sample code and I've never seen it used before. For an inline function which returns a type but the return value is not used, the author preceded the call with a (void). Does this actually do anything?

Example:

inline some_object& SomeClass::doSomething();

SomeClass o;

(void)o.doSomething();
Zhro
  • 2,546
  • 2
  • 29
  • 39
  • 1
    To squelch the source code analyzer's warning the caller is ignoring the return result. – WhozCraig May 23 '16 at 16:22
  • Suppress compiler warning about ignoring the return-value of the function. – barak manos May 23 '16 at 16:23
  • By casting to `void` it might not produce an unused value warning on some compiler set to some strict level of warning. So maybe it's intended to get clean compiles. Similarly, if you have a function with unused arguments (to match a signature, for instance for a QT signal), you can cast the arguments to `void` inside the function and still have a 'clean' compile with no warnings. – infixed May 23 '16 at 16:26

2 Answers2

3

This is typically done when using a tool like Lint which has been configured to issue a warning if you call a function and ignore its return value.

Sean
  • 60,939
  • 11
  • 97
  • 136
  • Note that it's not just lint-like tools that issue such warnings, compilers can also detect ignored function results and/or arguments, requiring casting to `void` to quiet the warning. – cmaster - reinstate monica May 23 '16 at 16:27
1

This is (IMO) a horrible practice that's fostered by some tools1 that give warnings about calling a function and ignoring what it returns.

The right way to deal with the problem is to give the tool a list of functions whose return values can reasonably be ignored. If the tool doesn't support that, it's probably useless and should be thrown away. In the case of a compiler, you may not be able to throw away the tool itself, and may have to settle for just globally disabling that warning.


1. Most often something like lint, but some compilers can do the same.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • My comment to Sean's answer applies to your answer as well: compilers may detect this as well. – cmaster - reinstate monica May 23 '16 at 16:29
  • @cmaster: A compiler that's sufficiently prone to issuing meaningless warnings *is* a lint (that also happens to generate code). – Jerry Coffin May 23 '16 at 16:33
  • I share your distaste for such chatty tools that require extra quirks on legit code to shut up. Yet, compilers like `gcc` (which I know can issue these warnings) are generally not recognized as linting tools. And you cannot stop using a compiler, you can just switch off the offending warning. As such, it would add to the understandability of your answer to add a comment on compilers. – cmaster - reinstate monica May 23 '16 at 16:59