为什么"函数名称"在C中评估为true,以及如何在其上发出警告

Mar*_*tin 11 c gcc-warning

我最近偶然发现了以下gcc 3.2.2编写ac程序的行为:

在if语句中,我忘记了函数的大括号,并写道:

if(myFunc)... 代替 if(myFunc())...

虽然我几乎每个警告都打开了,但这并没有产生错误.

它只是评估为true.为什么这首写法律代码?因为函数存在/有地址?有谁知道如何避免这样的错误,或者是否有一个我忽略的警告选项?这个问题在以后的gcc版本中是否能更好地解决?

这里是完整性的确切编译器调用:

 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
Run Code Online (Sandbox Code Playgroud)

(因为我被迫使用gcc 3.2.3,所以没有-Wextra)

Pau*_*l R 17

if (myFunc)相当于if (&myFunc),所以你正在测试一个函数的地址,当然它总是非零,即为真.

使用gcc 4.2.1,-Wall我收到以下警告:

myfunc.c:11: warning: the address of ‘myFunc’ will always evaluate as ‘true’

  • @Conrad:是的,每个有效的指针都保证与空指针的值相等. (3认同)