Coding With Fun
Home Docker Django Node.js Articles FAQ

An empty pointer can be used instead of nullptr


Jun 01, 2021 Article blog


Table of contents


The first thing to know is what an empty pointer is, and the empty pointer is void*

In C/C++ to avoid wild pointers (i.e. pointers do not point to any addresses), it is a good idea to initialize a pointer as soon as it is declared.

If it is not clear which variable the pointer points to for the time being, you can give NULL, such as:

int* p = NULL;

In addition to NULL the new standard for C++11 introduces nullptr to represent an empty pointer.

nullptr is neither an integer type nor a pointer type, nullptr type is std::nullptr_t which can be converted to any pointer type.

Why is it recommended to use nullptr instead of NULL?

This is because NULL is defined as a constant of 0 in C++ and problems occur when a function overload is encountered.

For example, when there are two functions:

  • void foo(int n)

  • void foo(char* s)

Function overload: C++ multiple similar functions of the same name to be declared in the same scope, and the list of parameters (number of arguments, type, order) of these functions of the same name must be different.

#include <iostream>
using namespace std;


void foo(int n) {
    cout << "foo(int n)" << endl;
}


void foo(char* s) {
    cout << "foo(char* s)" << endl;
}


int main()
{
    foo(NULL);
    return 0;
}

Compile the above code, and the result is shown in the following image, and the compiler suggests that both functions may match to produce ambiguity.

 An empty pointer can be used instead of nullptr1

With nullptr the compiler selects the function of foo(char* s) because nullptr is not an integer type.

#include <iostream>
using namespace std;


void foo(int n) {
    cout << "foo(int n)" << endl;
}


void foo(char* s) {
    cout << "foo(char* s)" << endl;
}


int main()
{
    foo(nullptr);
    return 0;
}

The results of the operation are shown in the following image:

 An empty pointer can be used instead of nullptr2

Therefore, when an empty pointer is required, nullptr is preferred instead of NULL

These are the reasons why the empty pointer of c++ is replacing NULL with nullptr I hope it will be helpful to everyone, and then students who want to learn more about C++ NULL

C?tutorial: https://www.w3cschool.cn/cpp/

C?micro-class: https://www.w3cschool.cn/minicourse/play/cppminicourse

Source: www.toutiao.com/a6854549524803748356/