Ignoring return values in C

Solution 1:

The common way is to just call foo(); without casting into (void).

He who has never ignored printf()'s return value, cast the first stone.

Solution 2:

I personally like the "unused" warnings, but on occasion there are instances where I have to ignore them (e.g., the write() to user, or fscanf(...,"%*s\n") or strtol() where the return value is unimportant and I just want the side effect of [maybe] moving the file pointer along.)

With gcc 4.6, it's getting quite tricky.

  • Casting to (void) no longer works.
  • Re-writing functions (especially variadic) is tedious and clumsy.
  • {ssize_t ignore; ignore=write(...);} throws up another warning (assigned-not-used).
  • write(...)+1 throws up yet another warning (computed-value-not-used).

The only good (if ugly) way to suppress these is to convert the return value into something that the compiler agrees that you can ignore.

E.g., (void)(write(...)+1).

This is apparently progress. (And +0 does not work, BTW.)

Solution 3:

One way to do this with Clang and GCC compilers is with a pragma:

    /* ... */

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result" 

    foo(); /* this specific unused-result warning gets ignored during compilation */

#pragma GCC diagnostic pop 

    /* ... */

The push-pop combination wraps the ignored directive so that warnings can be triggered elsewhere in your code. It should be easier for anyone reading your source code down the road to see what this code block does.

Solution 4:

One slightly more "beautiful" way of indicating unused results would be this:

/**
 * Wrapping your function call with ignore_result makes it more clear to
 * readers, compilers and linters that you are, in fact, ignoring the
 * function's return value on purpose.
 */
static inline void ignore_result(long long int unused_result) {
    (void) unused_result;
}

...

ignore_result(foo());

With C++, this may be extended to:

template<typename T>
inline void ignore_result(const T & /* unused result */) {}

Solution 5:

For a static code checker to be useful, it should report also the ignored return values, which can lead very often to difficult to track errors - or missing error handling.

So you should keep the (void) or deactivate the check for printf. Now you have several options for doing it in a readable manner. I use to wrap the function inside a new function like for example

void printf_unchecked(const char* format, ...)

where the not so nice cast takes place. Perhaps it's more practical to do it using a preprocessor macro in this case because of the varargs...