Difference between NULL and nullptr in C++

In this tutorial, we are going to learn about what is the difference between NULL & nullptr in C++.

NULL in C++

  • “NULL” in C++ by default has the value zero (0) OR we can say that, “NULL” is a macro that yields to a zero pointer i.e. no address for that variable.
  • In C-language, “NULL” is an old macro that is inherited in C++.

Let’s look at the example below that will help you to understand more clearly,

int var1 = NULL;
float var2 = NULL;

int *ptr_var = NULL;
  • So now if you try to print the value of var1, var2 & ptr_var each on a new line then you will get the output respectively as,
0
0
0
  •  However, the 1st two lines will generate a warning with the message saying “Converting from NULL to non-pointer type”.
  • Usually, however, “NULL” is just a synonym for zero and therein lies the problem: It is both a null pointer constant and arithmetic constant.
  • This can raise a problem if you pass “NULL” as a parameter to a function. Let’s understand this problem with the following code snippet,
//Program 1

#include <bits/stdc++.h> 
using namespace std; 
 
int Null_func(int N)  
{ 
    cout << "This function has an integer parameter" ; 
} 
   
int Null_func(char* N)  //Overloaded function
{ 
    cout << "This function has a character pointer type parameter" ;
} 
  
int main()  
{
    
  Null_func(NULL); //This should basically call the function having parameter of type character pointer.
   
  return 0;    
}
  • This program on compiling will generate an error saying,
error: call of overloaded ‘Null_func(NULL)’ is ambiguous
     Null_func(NULL);

  • So this ambiguity is generated because “NULL” is defined typically as (void *)0 & we know that NULL to integral type conversion is allowed. Due to this fact, whenever we try to call Null_func(NULL) function, ambiguity will be created.

nullptr in C++

  • So here is where the “nullptr” comes into the picture. nullptr, as the name indicates, is a keyword which is really a “null pointer” & will always remain a pointer. This means that if you try to assign it to the integer variable it will generate an error.
int var = nullptr;

This will cause an error. But it will work if it’s,

int *var = nullptr;

(Note:- nullptr is convertible to bool. )

  • Just like a “NULL”, nullptr is also comparable to any pointer type & implicitly convertible as well. Also, you cannot compare nullptr with integral type & it cannot be converted implicitly.
  • So now if we replace the “NULL” parameter in Program 1 by “nullptr” (without quotes) the output of that program will be,
This function has a character pointer type parameter
  • Hence we have removed the ambiguity caused by “NULL” by replacing it with the nullptr which cannot be converted to an integral type.

Thanks for reading!

Comment for any queries.

Leave a Reply

Your email address will not be published.