sashoalm
sashoalm

Reputation: 79725

Why was/is NULL used in C++?

The C++ standard defines the null pointer to be 0. In a lot of code I've seen the NULL macro used however.

Why is it so? If the standard defines NULL to be 0 anyway, why use a special constant for it?

Is it just an aesthetic choice, or is there a more practical reason for it? Or was there a reason in the past that is no longer valid, i.e. holdovers from older drafts of the C++ standard?

How and why did NULL begin to be used instead of 0?

Upvotes: 3

Views: 276

Answers (4)

Danvil
Danvil

Reputation: 23031

A pointer is not an integer - their types are different. So int* p = 0; somehow looks wrong, especially given the case the int* p = 5; is a compiler error.

People are using NULL (reference) to have a special word for a null pointer constant, i.e. indicating a pointer which points to nothing. But NULL is just a workaround and often realized as a macro which in C++ (often) resolves to the integer 0.

C++11 has introduced nullptr (reference) to solve this problem once and for all.

Upvotes: 1

Matthieu M.
Matthieu M.

Reputation: 300419

This is a leftover from C, where NULL is often defined as (void*)0. In C, because of conversion rules, it makes NULL implicitly convertible to any other pointer type while remaining non convertible to integer types:

int* a = NULL; /* OK */
int b = NULL;  /* ERROR */

C++ however does not have such loose type conversions, and therefore NULL is defined as 0 in C++. While this means that int b = NULL; is legal, compilers are generally smart enough to emit a warning if you do so as they recognized that NULL is a special macro thus preserving some of the type safety... when the warning works.

Of course, in C++11, one should use nullptr instead. In C++03 though even Stroustrup already recommended using 0 rather than a macro.

Upvotes: 4

tenfour
tenfour

Reputation: 36906

NULL is more descriptive than 0, and they have different fundamental meanings. 0 is an integer number, while NULL indicates something like "no value" or "points to nothing". Similarly PI is more descriptive in your code than 3.1415926535897.

This was a compromise until C++11 where you should be using the nullptr keyword. Now, in addition to the added clarity, you get actual compiler support for your intention. For example int x = NULL; doesn't really make much sense because even though NULL boils down to an integer, its meaning is not that of an integer. int x = nullptr; will properly error.

Upvotes: 2

cnluzon
cnluzon

Reputation: 1084

I would say it is just an influence of C programmers, where NULL was used as a standard value for initializing pointers.

Upvotes: 1

Related Questions