nullptr
Anonymous contributor
Published Nov 20, 2024
Contribute to Docs
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
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours