Easy Tutorial
❮ Cpp Standard Library Cpp Nested Loops ❯

C++ Null Pointer

C++ Pointers

When declaring a variable, if there is no specific address to assign, it is a good programming practice to assign a NULL value to the pointer variable. A pointer assigned a NULL value is called a null pointer.

The NULL pointer is a constant with a value of zero defined in the standard library. Consider the following program:

Example

#include <iostream>

using namespace std;

int main ()
{
   int  *ptr = NULL;

   cout << "The value of ptr is " << ptr;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

The value of ptr is 0

On most operating systems, programs are not allowed to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has a special significance; it indicates that the pointer is not intended to point to an accessible memory location. By convention, if a pointer contains the null value (zero value), it is assumed to point to nothing.

To check for a null pointer, you can use an if statement as follows:

if(ptr)     /* succeeds if ptr is not null */
if(!ptr)    /* succeeds if ptr is null */

Therefore, if all unused pointers are assigned a null value and avoid using null pointers, it can prevent the misuse of an uninitialized pointer. Often, uninitialized variables contain some garbage values, making the program difficult to debug.

C++ Pointers

❮ Cpp Standard Library Cpp Nested Loops ❯