Search code examples
c++castingsuppress-warnings

Is casting a function return to void an "old-style-cast" or not?


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?


Solution

  • 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, and const_cast) are less vulnerable to unintended effects and much easier to search for.

    2) not documented