C++ nullptr – The Modern Way to Say “No Address”
In C++, if a pointer doesn’t point anywhere, we say it’s null. Before C++11, we used NULL
. But now we have something better — nullptr
!
nullptr
is a special keyword that means “this pointer points to nothing.”
Why use nullptr?
- Type-safe – It’s only for pointers
- Modern – Recommended since C++11
- Prevents bugs – No accidental confusion with integers
Example: Using nullptr with Pointers
#include <iostream>
using namespace std;
void greet(int* p) {
if (p == nullptr) {
cout << "Pointer is null!" << endl;
} else {
cout << "Value: " << *p << endl;
}
}
int main() {
int* ptr = nullptr;
greet(ptr); // Will say "Pointer is null!"
int x = 42;
ptr = &x;
greet(ptr); // Will print the value
return 0;
}
#include <iostream>
using namespace std;
void greet(int* p) {
if (p == nullptr) {
cout << "Pointer is null!" << endl;
} else {
cout << "Value: " << *p << endl;
}
}
int main() {
int* ptr = nullptr;
greet(ptr); // Will say "Pointer is null!"
int x = 42;
ptr = &x;
greet(ptr); // Will print the value
return 0;
}
#include <iostream> using namespace std; void greet(int* p) { if (p == nullptr) { cout << "Pointer is null!" << endl; } else { cout << "Value: " << *p << endl; } } int main() { int* ptr = nullptr; greet(ptr); // Will say "Pointer is null!" int x = 42; ptr = &x; greet(ptr); // Will print the value return 0; }
nullptr vs NULL vs 0
NULL
– Old C-style (actually just 0)0
– Dangerous, could be confused with intnullptr
–Modern and safe (best choice)
Summary
nullptr
represents a null (empty) pointer- Use it to avoid bugs and write modern C++
- Always prefer
nullptr
overNULL
or0
So next time you want to say “this pointer goes nowhere,” say it like a pro — use nullptr
!