cpp-como-usar-nullptr

What is nullptr and how to use it in C++

  • 2 min

In C++11 and later versions, nullptr is a special literal that represents a null pointer (i.e., a pointer that does not point to a valid address).

Before C++11, we had to use NULL or 0. But this caused ambiguity errors, especially when working with overloaded functions and templates.

It also improves readability and helps prevent errors that are difficult to detect related to memory management.

It is recommended to use nullptr whenever possible instead of NULL or 0 to represent null pointers.

Declaring Null Pointers

To declare a null pointer in C++11 and later, we simply initialize it to nullptr. This ensures the pointer does not have a valid address assigned.

#include <iostream>

int main() {
    int* ptr = nullptr; // Pointer to int initialized to nullptr

    if (ptr == nullptr) {
        std::cout << "The pointer does not point to any valid address." << std::endl;
    }

    return 0;
}
Copied!

Here,

  • The pointer ptr is declared and initialized with nullptr.
  • This means it does not have any valid memory address assigned.

Advantages of nullptr

The main advantage of nullptr lies in its ability to improve code safety and clarity. For example, consider this scenario:

#include <iostream>

void func(int x) {
    std::cout << "func(int) called with " << x << std::endl;
}

void func(int* ptr) {
    if (ptr) {
        std::cout << "func(int*) called with valid pointer." << std::endl;
    } else {
        std::cout << "func(int*) called with null pointer." << std::endl;
    }
}

int main() {
    func(0);       // Ambiguous with NULL, interpreted as `func(int)`
    func(nullptr); // Clear: calls `func(int*)` with null pointer

    return 0;
}
Copied!

In this example,

  • func(0) can be ambiguous, as 0 could be interpreted as an integer instead of a pointer.
  • With nullptr, there is no ambiguity: func(nullptr) calls the overload that accepts a pointer (func(int*)).