Home Item 6 - nullptr (English)
Post
Cancel

Item 6 - nullptr (English)

Null Pointer Constant (nullptr)

Stop using pointers to check whether they’re equal to 0 or NULL!!!

In C++11, the nullptr null pointer constant was introduced, which can be used instead of the traditional NULL or 0 to improve code clarity and safety.

Here’s a simple example

Let’s look at the code directly

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void foo(int* ptr) {
    if (ptr == nullptr) {
        std::cout << "Pointer is null." << std::endl;
    } else {
        std::cout << "Pointer is not null." << std::endl;
    }
}

int main() {
    int* ptr = nullptr; // Initialize pointer with nullptr
    foo(ptr); // Call function and pass nullptr

    int* ptr2 = 0; // Initialize pointer with integer 0
    foo(ptr2); // Call function and pass integer 0

    return 0;
}

When to use:

  1. Pointer comparison: When you need to check whether a pointer is null in the code, using nullptr is clearer and avoids confusion with integers.
  2. Function calls: When passing a null pointer to a function as a parameter, using nullptr expresses the intent clearly instead of using 0 or NULL.
  3. new operator: When dynamically allocating memory, using nullptr as the initial value to initialize the pointer is safer because it indicates that the pointer is empty rather than pointing to an unknown address.
  4. Used with templates: In C++, nullptr is often used in template programming to make the code more consistent and generic.

People grow, and programming languages grow too, so let’s grow together! Cheers!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍