Learn++ Lesson 41: Null Pointers in C++ Programming
A null pointer is a pointer that does not point to a valid memory address. In modern C++, nullptr clearly represents that empty state.
Check a pointer before using it
#include <iostream>
int main() {
int *ptr = nullptr;
if (ptr == nullptr) {
std::cout << "Pointer is null";
}
return 0;
}
Output:
Pointer is null
The pointer ptr is initialized with nullptr. The condition compares it with nullptr, so the message is printed. Checking first helps avoid dereferencing a pointer that does not refer to a valid object.
Why null pointers matter
- They represent missing or unavailable data explicitly.
- They let a program test pointer validity before dereferencing.
- They help prevent undefined behavior caused by using an invalid address.
What you practice in Learn++
- Initializing a pointer with
nullptr. - Comparing a pointer with
nullptr. - Recognizing the safe branch before pointer use.
Today's challenge
Complete the control-structure condition so the program prints Pointer is null:
#include <iostream>
int main() {
int *ptr = nullptr;
if (___ == nullptr) {
std::cout << "Pointer is null";
}
return 0;
}
The unique answer is ptr: it is the only pointer declared in the program and must be compared with nullptr.