Is NULL always defined as 0?

NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a void pointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can’t always tell when a pointer is needed).  

Showing Answers 1 - 3 of 3 Answers

kbjarnason

  • Jul 2nd, 2010
 

In a pointer context, an integer constant value of 0 (cast to void * or not) becomes a null pointer constant.  If assigned to a pointer, comparing the pointer to NULL will evaluate as true.

That is, char *ptr = 0;  if ( ptr == NULL ) will be true.

Oddly, the converse is not required to be true.  That is, if you were to bitwise evaluate the value of a known null pointer, there is no necessity that the value you discover is actually 0... and there is (or was) at least one implementation where null pointers did not evaluate, bitwise, as 0.  On the other hand, if ( ptr == 0 ) or if (ptr == NULL) still evaluated true as expected.  As long as the code works as expected, the implementation can do all sorts of weird things.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions