Using NULL in C++? [duplicate]
Solution 1:
In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
Solution 2:
The downside of NULL in C++ is that it is a define for 0. This is a value that can be silently converted to pointer, a bool value, a float/double, or an int.
That is not very type safe and has lead to actual bugs in an application I worked on.
Consider this:
void Foo(int i);
void Foo(Bar* b);
void Foo(bool b);
main()
{
Foo(0);
Foo(NULL); // same as Foo(0)
}
C++11 defines a nullptr
that is convertible to a null pointer but not to other scalars. This is supported in all modern C++ compilers, including VC++ as of 2008. In older versions of GCC there is a similar feature, but then it was called __null
.
Solution 3:
From crtdbg.h (and many other headers):
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
Therefore NULL
is 0
, at least on the Windows platform. So no, not that I know of.
Solution 4:
I never use NULL in my C or C++ code. 0
works just fine, as does if (ptrname)
. Any competent C or C++ programmer should know what those do.