Understanding nullptr in C++ (original) (raw)

Last Updated : 9 Jun, 2026

In C++, NULL was traditionally used to represent null pointers. However, its use can lead to ambiguity in function overloading and unintended type conversions. To overcome these issues, C++11 introduced nullptr, a type-safe keyword that clearly represents a null pointer and eliminates ambiguity in pointer operations.

#include <bits/stdc++.h> using namespace std;

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

}

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

}

int main() { // Ideally, it should have called fun(char *), // but it causes compiler error. fun(NULL);
}

`

**Output

cpp:20:8: error: call of overloaded 'fun(NULL)' is ambiguous
20 | fun(NULL);

**Explanation

How nullptr Solves the Problem

Replacing NULL with nullptr removes ambiguity because nullptr is a distinct pointer type.

#include using namespace std;

void fun(int N) { cout << "fun(int)"; }

void fun(char* s) { cout << "fun(char*)"; }

int main() { fun(nullptr); }

`

Type Safety of nullptr

Unlike NULL, nullptr cannot be assigned to integer types.

C++ `

#include <stdio.h>

int main() { int x = nullptr; // Error }

`

**Output

Compiler Error

**Explanation

nullptr in Conditional Statements

nullptr can be used in conditions to check pointer validity.

C++ `

#include using namespace std;

int main() { int* ptr = nullptr;

if (ptr)
    cout << "true";
else
    cout << "false";

}

`

**Explanation: A null pointer evaluates to false in a conditional expression, while a valid pointer evaluates to true.

Comparison Behavior of nullptr

The nullptr keyword supports safe and well-defined comparisons with pointer types.

nullptr_t Type Behavior

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

**Explanation