How to define NULL using #define

#define MYNULL NULL

is the safest, I see no reason in doing so but if you really want to, go ahead. Here's how C and C++ do it respectively:

#define NULL 0 //C++
#define NULL ((void*)0) //C

Generally speaking, defining 0 for NULL is a bad habit, you actually want it to be part of the language. C++0x adresses this.

This is what Bjarne Stroustrup has to say on this:

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.


What exactly is the problem with getting your NULL from where you're supposed to?, i.e.,

#include <stddef.h>

or

 #include <cstddef>

as alluded to in @Johannes Rudolph's answer, any trickery you do is not likely be very future proof in the face of things like nullptr etc.

EDIT: while stdlib (and many others) are mandated to include a NULL, stddef is the most canonical header [and has been for decades].

PS In general, it's just a bad idea to get involved in this sort of trickery unless you have a really good reason. You didnt expand on the thinking that led you to feeling the need to do this. If you could add some detail on that, it's likely to lead to better answers. Other people answering the question should have pointed this out in their answers too, but I guess does FGITW as FGITW does best :D

EDIT 2: As pointed out by @Yossarian: The single justification for doing this is if there isnt a NULL defined in an appropriately language-agnostic form elsewhere in your system. Naked compilers with no headers and/or if you're writing your own custom standard library from scratch are examples of such a circumstance. (In such a bare-bones scenario, I'd go with @lilburne's answer (be sure to use 0 as much as possible))


#ifdef __cplusplus
#define MYNULL 0
#else
#define MYNULL ((void*)0)
#endif

will work in both of them.

Tags:

C++

C

Null