Is NULL always false?

前端 未结 13 1612
孤城傲影
孤城傲影 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:28

    The 'C' language dates from an era where (void*)0 could actually be a valid pointer. It is not that long ago, the 8080 and Z80 microprocessors had an interrupt vector at address 0. Faced with such architecture choices, it couldn't do anything but let a header file declare the value of NULL. There were some compilers out there, now long forgotten, where NULL was not equal to (void*)0 (0xffff was the next alternative), thus giving your if() statement undefined behavior.

    C++ mercifully put an end to this, a null pointer is assignable from and testable against 0.

提交回复
热议问题