← Back to C++ Course | Chapter 16: Modern C++ | Lesson 3 of 9

C++ nullptr

What is nullptr?

nullptr is a dedicated null-pointer literal introduced in C++11 with its own type, std::nullptr_t, which implicitly converts to any pointer type but not to an integer. This closes a long-standing source of bugs from C's convention of using the integer 0 to mean "no pointer."

Example: What is nullptr?

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	std::cout << (ptr == nullptr) << std::endl;
	return 0;
}

nullptr vs. NULL

In C and older C++, NULL is typically just a macro for the integer literal 0, which means the compiler can't always tell whether you meant a null pointer or the number zero -- this ambiguity becomes a real problem in overloaded functions that accept both a pointer and an int parameter.

Example: nullptr vs. NULL

cpp
#include <iostream>
#include <cstddef>

int main() {
	int *ptr1 = nullptr;
	int *ptr2 = NULL;
	std::cout << (ptr1 == ptr2) << std::endl;
	return 0;
}

Overloading with nullptr

Because nullptr has its own pointer-only type, passing it to an overloaded function unambiguously selects the pointer overload, whereas passing NULL (really just 0) to the same overloaded functions would incorrectly call the integer version -- a classic C++98 gotcha that nullptr was specifically designed to fix.

Example: Overloading with nullptr

cpp
#include <iostream>

void show(int x) { std::cout << "int: " << x << std::endl; }
void show(char *p) { std::cout << "pointer" << std::endl; }

int main() {
	show(nullptr);
	return 0;
}

Checking Pointer Validity

Dereferencing a null pointer -- reading or writing through *ptr when ptr is nullptr -- causes a segmentation fault that immediately crashes the program. Checking if (ptr != nullptr) (or simply if (ptr)) before dereferencing is the standard guard against this.

Example: Checking Pointer Validity

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	if (ptr != nullptr) {
		std::cout << *ptr << std::endl;
	} else {
		std::cout << "Pointer is null, skipping dereference" << std::endl;
	}
	return 0;
}

Passing nullptr to Functions

Passing nullptr as a function argument is a clear, type-safe way to signal "no value provided" for an optional pointer parameter, letting the function branch on whether real data was supplied without needing a separate boolean flag.

Example: Passing nullptr to Functions

cpp
#include <iostream>

void process(int *data) {
	if (data == nullptr) {
		std::cout << "No value provided" << std::endl;
	} else {
		std::cout << *data << std::endl;
	}
}

int main() {
	process(nullptr);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.