The Null Pointer Convention

1.The Null Pointer Convention

After a pointer is declared, but before it has been assigned a value, it will contain an arbitrary value. Should you try to use the pointer prior to giving it a value, you will probably crash not only your program, but perhaps even the operating system of your computer (a very nasty type of error!). While there is no sure way to avoid using an uninitialized pointer, C++ programmers have adopted a procedure that helps prevent some errors. By convention, if a pointer contains the null (zero) value, it is assumed to point to nothing. Thus, if all unused pointers are given the null value and you avoid the use of a null pointer, you can avoid the accidental misuse of an uninitialized pointer. This is a good practice to follow.

Any type of pointer can be initialized to null when it is declared. For example, the following initializes p to null:
float *p = 0; // p is now a null pointer

To check for a null pointer, use an if statement, like one of these:
if(p) // succeeds if p is not null
if(!p) // succeeds if p is null

If you follow the null pointer convention, you will avoid many problems when using pointers.
Share on Google Plus