C++ nullptr
In this page:
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?
#include <iostream>
int main() {
int *ptr = nullptr;
std::cout << (ptr == nullptr) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <cstddef>
int main() {
int *ptr1 = nullptr;
int *ptr2 = NULL;
std::cout << (ptr1 == ptr2) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: