4

Problem statement

I use a return integer to propagate errors through my code. I would like gcc to provide me with a warning if I accidentally forget to propagate the error (i.e. when I forget to use the return integer).

Example

Consider this very simple example test.c:

// header
int test ( int a );

// function
int test ( int a )
{

  if ( a<0 ) return 1;

  return 0;
}

// main program
int main ( void )
{

  int a = -10;

  test(a);

  return 0;
} 

Expected behavior

$ gcc -Wunused-result main.c
Warning: main.c:19 ... unused return ...

or alternatively using Wall or Wextra or another option.

Needless to say, my compiler does not provide the warning with any of these options. One of my mistakes already took me frustratingly long to find...

Tom de Geus
  • 5,625
  • 2
  • 33
  • 77

2 Answers2

2
// header
int test ( int a )  __attribute__ ((warn_unused_result));

// function
int test ( int a )
{

  if ( a<0 ) return 1;

  return 0;
}

// main program
int main ( void )
{

  int a = -10;

  test(a);

  return 0;
}

It should work now.

anothertest
  • 979
  • 1
  • 9
  • 24
2

In gcc and clang, you can mark specific functions with the warn_unused_result attribute and it will let you know if you ignore the result (assuming you're not using the -Wno-unused-result flag, of course).

Unfortunately, I'm not aware of a way to get those compilers to apply this to all functions globally, you have to do it explicitly on a case-by-case basis.

In any case, doing it globally would cause some rather annoying behaviour from things like printf where you may not care about the return code.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • The irony is that there is no such thing as not caring about the return of `printf` which isn't equivalent to willfully neglecting possible errors, possibly resulting in your program misbehaving in ways your users would find bad but inscrutable. (Unless you're checking `errno` or `ferror(stdout)` after every `printf`. Of course, the fact that there are three different ways in C's design to notice errors from I/O functions is a big part of why people end up with good reasons to ignore return values all over the place.) – mtraceur May 25 '22 at 05:57
  • Of course, `fprintf` is another story, because *obviously* no good program writes *logging* or *diagnostics* to `stdout`, those go on `stderr`, and sometimes it makes sense to have `stderr` be a "best effort" thing where if you can't write to it, you just gracefully degrade to silent operation instead (but even then, many programs should exit with an error status immediately when they can't log for mysterious inexplicable reasons - not if lives depend on it running of course, but if it's a webserver or something it's worth seriously considering, and definitely if it's a simple CLI command). – mtraceur May 25 '22 at 06:07