Open In App

Understanding nullptr in C++

Last Updated : 05 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Consider the following C++ program that shows problem with NULL (need of nullptr)
 

CPP
// C++ program to demonstrate problem with NULL
#include <bits/stdc++.h>
using namespace std;

// function with integer argument
void fun(int N)   { cout << "fun(int)"; return;}

// Overloaded function with char pointer argument
void fun(char* s)  { cout << "fun(char *)"; return;}

int main() 
{
    // Ideally, it should have called fun(char *),
    // but it causes compiler error.
    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
// This program compiles (may produce warning)
#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
// This program does NOT compile
#include<stdio.h>
int main() 
{
   int x = nullptr;
}

Output: 

Compiler Error


As a side note, nullptr is convertible to bool. 
 

CPP
// This program compiles
#include<iostream>
using namespace std;

int main() 
{
   int *ptr = nullptr;

   // Below line compiles
   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++
// C++ program to show comparisons with nullptr
#include <bits/stdc++.h>
using namespace std;

// Driver program to test behavior of nullptr
int main()
{
    // creating two variables of nullptr_t type 
    // i.e., with value equal to nullptr
    nullptr_t np1, np2;

    // <= and >= comparison always return true
    if (np1 >= np2)
        cout << "can compare" << endl;
    else
        cout << "can not compare" << endl;

    // Initialize a pointer with value equal to np1
    char *x = np1;  // same as x = nullptr (or x = NULL
                    // will also work) 
    if (x == nullptr)
        cout << "x is null" << endl;
    else
        cout << "x is not null" << endl;

    return 0;
}

Output : 

can compare
x is null



 



Previous Article
Next Article

Similar Reads

Understanding static_assert in C++ 11
What is static assertion? Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression. Performs compile-time assertion checking Syntax: static_assert( constant_exp
6 min read
Understanding Lvalues, PRvalues and Xvalues in C/C++ with Examples
LValue and RValue in C Background Quite a few of you who are about to read this article, might be looking for clarification of what used to be basic: rvalues were thingies that can pop up on the right of an assignment operator, and lvalues were thingies that belong on the left or right an assignment operator. After all, this is how k&amp;R distingu
17 min read
OpenCV | Understanding Contrast in an Image
In OpenCV, changing the contrast of an image is a very basic task to perform. By changing the image contrast, it is meant to change the value of each and every image pixel. This change can be done by either multiplying or dividing (means to multiply each pixel with value &lt; 1) the pixel values of the image, by any constant. To increase the contra
2 min read
OpenCV | Understanding Brightness in an Image
In OpenCV, changing the brightness of an image is a very basic task to perform. By changing the image brightness, it is meant to change the value of each and every image pixel. This change can be done by either increasing or decreasing the pixel values of the image, by any constant. To increase the brightness levels of the image, simply add a const
2 min read
Understanding "register" keyword in C
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using the register keyword. The keyword register hints to the compiler that a given variable can be put in a register. It's the compiler's choice to put it in a register or not. Generally, compilers themselves do optimi
3 min read
Understanding "volatile" qualifier in C | Set 2 (Examples)
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the curre
6 min read
Understanding "volatile" qualifier in C | Set 1 (Introduction)
In spite of tons of literature on C language, "volatile" keyword is somehow not understood well (even by experienced C programmers). We think that the main reason for this is due to not having real-world use-case of a 'volatile' variable in typical C programs that are written in high level language. Basically, unless you're doing some low level har
5 min read
Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
Given a URL as a string open it using a C++ code in Microsoft Windows OS. Example: Input : https://www.geeksforgeeks.org/ Output : The site opened in your browser. // C++ program to open a URL in browser. // This program is written on for Microsoft // Windows OS #include &lt;bits/stdc++.h&gt; #include &lt;windows.h&gt; using namespace std; int main
5 min read
Understanding constexpr Specifier in C++
constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template met
5 min read
Article Tags :
Practice Tags :