The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The Null Pointer

Remember how you can assign a character or string to be null? If you don't remember, check out HERE. The null character in a string denotes the end of a string, however, if a pointer were to be assigned to the null pointer, it points to nothing. The null pointer is often denoted by 0 or null. The null pointer is often used in conditions and/or in logical operations.

#include <iostream.h>

int main()
{
  int x = 12345;
  int* px = &x;

  while (px) {
    cout << "Pointer px points to something\n";
    px = 0;
  }

  cout << "Pointer px points to null, nothing, nada!\n";

  return 0;
}

If pointer px is NOT null, then it is pointing to something, however, if the pointer is null, then it is pointing to nothing. The null pointer becomes very useful when you must test the state of a pointer, whether it has a value or not.


Last Update: 2005-12-05