How to set a pointer to null in C++

Hello readers! In this tutorial, we are going to learn how we can set a pointer to null in C++.

A null pointer contains a constant that does not point to any valid objects or functions. Null pointers can be used in many cases:

  • To initialize a pointer
  • It tells errors in the pointer return procedure.
  • It tells us that it is the end of the list of unknown lengths.

A null pointer points to an integer constant whose value is zero.

Let’s see a code as an example for the same.

C++ Code: Set a pointer to null

#include <iostream>
using namespace std;
int main () {
   int  *ptr = NULL;           // set ptr to NULL
   cout << "The value of pointer will be " << ptr ; 
   return 0;
}

Output:

The value of pointer will be 0

Explanation of the C++ code

We will take a pointer ptr and set its value to NULL and prints its value. The value comes up to be zero(0).


That’s it for this tutorial I hoped you liked it.

Keep learning!

Leave a Reply

Your email address will not be published.