Coverity has complained that various function calls in our codebase are not checking the return value.
Unchecked return value (CHECKED_RETURN)3. check_return: Calling Append without checking return value (as is done elsewhere 73 out of 78 times).
In the past, we would have simply resolved this issue (after double-checking that the return value really was not important) by casting the return to void
(as discussed here):
(void)Foo.Append(bar);
However, we are moving towards enabling all warnings, and treating warnings as errors, so I'm a little concerned that the above code will generate an old-style-cast
diagnostic. If that's the case, I will need to modify our code to the considerably uglier format:
static_cast<void>( Foo.Append(bar) );
However, both gcc and clang seem to be able to compile this code (the first form) without complaining. So I suppose the final form of my question is this: Is casting a function return to void
considered an exception to the rule as far as C-style casts are concerned? Or do I need to double check my code and see if the lines in question aren't actually being included in those builds?
Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded. Follow this answer to receive notifications.
Function style casts bring consistency to primitive and user defined types. This is very useful when defining templates. For example, take this very silly example: template<typename T, typename U> T silly_cast(U const &u) { return T(u); }
C++ provides a variety of ways to cast between types: static_cast. reinterpret_cast. const_cast.
It's fine.
(void) f(x);
is always equivalent to a static_cast
as per [expr.static.cast]/6
:
Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression.
Converting the result of a function to void
is the way to make an expression a discard-value-expression. Now, the C++ way should be static_cast<void>(...)
but (void) ...
is an idiom (and is shorter).
Since the latter is well-defined and really common in codebases, gcc1 and clang2 made it not trigger Wold-style-cast
.
It's well-defined, recognized by major compilers. It's fine.
1)g++ documentation --- 3.5 Options Controlling C++ Dialect
-Wold-style-cast
(C++ and Objective-C++ only)
Warn if an old-style (C-style) cast to a non-void type is used within a C++ program. The new-style casts (dynamic_cast
,static_cast
,reinterpret_cast
, andconst_cast
) are less vulnerable to unintended effects and much easier to search for.
2)not documented
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