C++ nullptr
Anonymous contributor
Published Nov 20, 2024
The nullptr keyword in C++ represents a null pointer, ensuring type safety and clarity in pointer operations. Introduced in C++11, it replaces the traditional NULL macro and eliminates ambiguity in comparisons and function overloads involving pointers.
Syntax
std::nullptr_t variable_name = nullptr;
variable_name: The name of the pointer variable initialized withnullptr.
The above operation assigns a null value to a pointer, ensuring it does not point to any valid memory address.
Example
This example initializes a pointer with nullptr and then checks its value:
#include <iostream>int main() {int* ptr = nullptr; // Initialize the pointer to nullptrif (ptr == nullptr) {std::cout << "The pointer does not point to any memory location." << std::endl;}return 0;}
This example results in the following output:
The pointer does not point to any memory location.
In this example, nullptr ensures the pointer is safely initialized and easily checked, reducing the risk of undefined behavior from uninitialized pointers.
All contributors
- Anonymous contributor
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours