Ignoring return values in C Ignoring return values in C c c

Ignoring return values in C


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.


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.)


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.