C++ - pointer null value

In good C/C++ programming habits, when declaring a variable, it is best to give the variable an appropriate initial value, otherwise unpredictable errors may occur, such as uninitialized pointers. If a pointer does not have a legal pointer, we basically initialize it as follows:

void TestPtr()
{
	int* p1 = NULL;
	int* p2 = 0;
	// ……
}

But in C++ we recommend using this:

int* p3 = nullptr;

In the former, NULL and 0 are actually equivalent in C++ and are not standardized. NULL is actually a macro . In the traditional C header file (stddef.h), you can see the following code:

#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif

If no macro is defined, NULL is defined as 0 in cplusplus. As you can see, NULL may be defined as a literal constant 0, or as a constant of an untyped pointer (void*). No matter what definition is adopted, you will inevitably encounter some troubles when using null-valued pointers, such as:

 

The original intention of the program is to call the pointer version of the f(int*) function through f(NULL), but because NULL is defined as 0, it goes against the original intention of the program.

In C++98, the literal constant 0 can be either an integer number or an untyped pointer (void*) constant, but the compiler treats it as an integer constant by default. If you want to treat it as To use it in pointer mode, it must be cast to (void *)0.

Notice:

  1. When using nullptr to represent a pointer null value, there is no need to include the header file because nullptr was introduced as a new keyword in C++11.
  2. In C++11, sizeof(nullptr) occupies the same number of bytes as sizeof((void*)0).
  3. In order to improve the robustness of the code, it is recommended to use nullptr when subsequently representing the pointer null value .

Guess you like

Origin blog.csdn.net/m0_49687898/article/details/131348777