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

前端 未结 5 2111
粉色の甜心
粉色の甜心 2020-12-31 11:14

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

5条回答
  •  一整个雨季
    2020-12-31 11:57

    myFunc, since its the name of a function will always evaluate to true because its a pointer. More specifically it has to be a non-null pointer because you will be needing to dereference it. A null pointer would evaluate to false.

    In short, there does not seem to be a way for the compiler to tell you that you've made a mistake.

    What you need to do is to have some unit tests that separately invoke the true and false responses so that you can tell that you've actually called the function.

提交回复
热议问题