Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a "function name" evaluate to true in C and how to get warned on it

Tags:

c

gcc-warning

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)

like image 243
Martin Avatar asked Dec 01 '10 19:12

Martin


2 Answers

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’

like image 128
Paul R Avatar answered Sep 24 '22 10:09

Paul R


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.

like image 24
abelenky Avatar answered Sep 23 '22 10:09

abelenky