Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a pointer to null [closed]

Tags:

c++

c++11

There are three ways (that I'm aware of) to initialize a pointer to a null value :

1) Value initialization

T a = T(); // T is a pointer type
T a{};     // brace initializers don't suffer from the most vexing parse

Even though a typedef is required, this form is met in non generic code as well, eg

typedef int* ip; 
int *p = ip();

2) Set to nullptr manually

int *p = nullptr;

3) Set to a valid nullpointer-constant implicitly convertible to any pointer-type

int *p = NULL;

  • What are the pros and cons of each method ?

  • Are there uses case where each method is considered best fitting?

like image 406
Nikos Athanasiou Avatar asked Jul 24 '26 04:07

Nikos Athanasiou


1 Answers

Stroustroup always told us to us to us

 TYPE *var = 0 ;

In ye olde days of C++ there was little standardization of libraries. Doing

TYPE *var = NULL ; 

would often give different results when the definition of NULL was not standardized. Some compilers picked up the C definition.

C++ needed

#define NULL (0)

to work right while C headers generally had

#define NULL ((void*)0)

Thus, 0 became the accepted method for setting null pointers.

With the standard changes, there might be a shift to nullptr.

like image 101
user3344003 Avatar answered Jul 25 '26 21:07

user3344003