GCC feature request: warn on "if (function_name)"

From: Jamie Lokier
Date: Fri Feb 13 2004 - 23:48:45 EST


Ross Dickson wrote:
> The fix is to put the brackets back on "!need_resched()" so that we call
> the function and test its return value - not just test the function pointer!

[ Ross' bug was writing "if (!need_resched)" instead of
"if (!need_resched())" ]

I'm very surprised GCC doesn't warn about that. A quick test confirms
GCC 3.2.2 at least doesn't.

So, this is a feature request:

- Warn when a function name is tested in a boolean context.
(A function pointer variable or expression should not be warned for).

By boolean context I mean any place where a function name is
used as a value and tested against zero. Some examples:

if (function_name)
if (function_name && ( <some other expression> ))
if (function_name != 0)
if (function_name == 0)
if (!function_name)
x = function_name ? a : b;

- Don't warn if there are two levels of parantheses.

I know it's occasionally useful to test the NULL-ness of a functin
name, of weak symbols. In most cases, though, it's a bug. If you
really want to check a weak symbol, just write "if ((symbol))". That
syntax is already well known for testing the result of an assignment,
as in "if ((x = 1))" does not yield a warning but "if (x = 1)" does.

Perhaps a later GCC than 3.2.2 already has this test; if someone is
able to check, that would be nice.

Thanks muchly :)
-- Jamie
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/