Consider the following C++ program that shows problem with NULL (need of nullptr)
CPP
#include <bits/stdc++.h>
using namespace std;
void fun( int N) { cout << "fun(int)" ; return ;}
void fun( char * s) { cout << "fun(char *)" ; return ;}
int main()
{
fun(NULL);
}
|
Output:
16:13: error: call of overloaded 'fun(NULL)' is ambiguous
fun(NULL);
What is the problem with above program?
NULL is typically defined as (void *)0 and conversion of NULL to integral types is allowed. So the function call fun(NULL) becomes ambiguous.
CPP
#include<stdio.h>
int main()
{
int x = NULL;
}
|
How does nullptr solve the problem?
In the above program, if we replace NULL with nullptr, we get the output as “fun(char *)”.
nullptr is a keyword that can be used at all places where NULL is expected. Like NULL, nullptr is implicitly convertible and comparable to any pointer type. Unlike NULL, it is not implicitly convertible or comparable to integral types.
CPP
#include<stdio.h>
int main()
{
int x = nullptr;
}
|
Output:
Compiler Error
As a side note, nullptr is convertible to bool.
CPP
#include<iostream>
using namespace std;
int main()
{
int *ptr = nullptr;
if (ptr) { cout << "true" ; }
else { cout << "false" ; }
}
|
Output:
false
There are some unspecified things when we compare two simple pointers but comparison between two values of type nullptr_t is specified as, comparison by <= and >= return true and comparison by < and > returns false and comparing any pointer type with nullptr by == and != returns true or false if it is null or non-null respectively.
C
#include <bits/stdc++.h>
using namespace std;
int main()
{
nullptr_t np1, np2;
if (np1 >= np2)
cout << "can compare" << endl;
else
cout << "can not compare" << endl;
char *x = np1;
if (x == nullptr)
cout << "x is null" << endl;
else
cout << "x is not null" << endl;
return 0;
}
|
Output :
can compare
x is null
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Jul, 2021
Like Article
Save Article