Is NULL always false?

前端 未结 13 1625
孤城傲影
孤城傲影 2020-11-27 04:44

Is it safe to assume that NULL always translates to false in C?

void *somePtr = NULL;

if (!somePtr) {
  /* This will always be executed? */
}
<         


        
13条回答
  •  死守一世寂寞
    2020-11-27 05:17

    Yes, mostly.

    First off, NULL is a typedef. I could royally screw you over by saying in a previously included header

    #define NULL 1

    This might not make a lot of sense, but since when has other people's code ever made sense? :)

    Also, while it's probably syntactically safe, it's not semantically correct. NULL means "nothing", neither true or false or a boolean value or int or string. It means "a symbol for nothing". So testing for NULL is more like a philisophical issue: If a tree falls in the forest, and if(listener), does it make a sound?

    Do everyone a favor and be clear about testing against NULL.

提交回复
热议问题