warn_unused_result
gcc has a neat attribute that helps you check that function return codes are used.
For example, I have a function dcc_timeout_arm in distcc which uses longjmp and so returns a second time with an error if the timeout fails. So it's absolutely critical that the error return code be checked, or the code can't possibly work correctly.
In a earlier draft of the code I forgot to check it in some places. Unfortunately for me the non-error path works fine, but the error path would always fail. Of course error paths are notoriously poorly tested.
Therefore:
#ifdef __GNUC__ # define WARN_UNUSED __attribute__((warn_unused_result)) #else # define WARN_UNUSED #end ... int dcc_timeout_arm(int timeout, int) WARN_UNUSED;
So this gives a warning:
dcc_timeout_arm(5, DCC_PHASE_CONNECT);
and this is correct:
if ((ret = dcc_timeout_arm(5, DCC_PHASE_CONNECT)))
goto out; */
Great stuff. In terms of Rusty's module interface continuum, we just went from "6: follow common convention (check return codes) and you'll get it right" to "2: compiler will warn if you get it wrong." Build with -Werror and you get up to "1: the compiler won't let you get it wrong."
I hope gcc gains more attributes like this in the future. It would be good to get things like in Splint to check more invariants.
I had thought it would be nice if there were a global option to warn about ignored return values. The gcc team say it's not good, and on reflection I agree:
10.11 Certain Changes We Don't Want to Make
[....]
Warning when a non-void function value is ignored.
C contains many standard functions that return a value that most programs choose to ignore. One obvious example is printf. Warning about this practice only leads the defensive programmer to clutter programs with dozens of casts to void. Such casts are required so frequently that they become visual noise. Writing those casts becomes so automatic that they no longer convey useful information about the intentions of the programmer. For functions where the return value should never be ignored, use the warn_unused_result function attribute.
posted Wed 11 Aug 2004 in /software/languages/C | link
Archives 2008: Apr Feb 2007: Jul May Feb Jan 2006: Dec Nov Oct Sep Aug Jul Jun Jan 2005: Sep Aug Jul Jun May Apr Mar Feb Jan 2004: Dec Nov Oct Sep Aug Jul Jun May Apr Mar Feb Jan 2003: Dec Nov Oct Sep Aug Jul Jun May
Copyright (C) 1999-2007 Martin Pool.