nullptr

Anonymous contributor's avatar
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 with nullptr.

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 nullptr
if (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

Contribute to Docs

Learn C++ on Codecademy