I recently stumbled across the following behaviour of gcc 3.2.2 writing a c program:
In an if statement I forgot the braces of a function and wrote:
if(myFunc)...
instead of if(myFunc())...
This did not generate an error neither a warning although I have pretty much every warning turned on.
It simply evaluated to true
.
Why is this writing legal code in the first place ?
Because the function exists/has an address ?
Does anyone know how one could avoid such mistakes or if there is a warning option I overlooked ? Is this issue better solved in later gcc versions ?
Here the exact compiler call for completeness:
msp430-gcc -g -Os -mmcu=msp430x1611 -Wall -W -Wfloat-equal -Wundef -Wshadow -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wwrite-strings -Wsign-compare -Waggregate-return -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations
-Wredundant-decls -Wnested-externs -Wimplicit-function-declaration -Werror
(Since I'm forced to use gcc 3.2.3 there is no -Wextra)
if (myFunc)
is equivalent to if (&myFunc)
, so you're testing the address of a function, which of course will always be non-zero, i.e. true.
With gcc 4.2.1 and -Wall
I get the following warning:
myfunc.c:11: warning: the address of ‘myFunc’ will always evaluate as ‘true’
myFunc
is simply the memory address of the function, and is non-zero.
Your if-statement is pretty much the same as writing:
if (0x08451234) { ... }
And as a non-zero value, it is true
.
No warning seems appropriate, as it is valid and even somewhat common to test function-pointers to see if they are NULL or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With