205

In the early days of C++ when it was bolted on top of C, you could not use NULL as it was defined as (void*)0. You could not assign NULL to any pointer other than void*, which made it kind of useless. Back in those days, it was accepted that you used 0 (zero) for null pointers.

To this day, I have continued to use zero as a null pointer but those around me insist on using NULL. I personally do not see any benefit to giving a name (NULL) to an existing value - and since I also like to test pointers as truth values:

if (p && !q)
  do_something();

then using zero makes more sense (as in if you use NULL, you cannot logically use p && !q - you need to explicitly compare against NULL, unless you assume NULL is zero, in which case why use NULL).

Is there any objective reason to prefer zero over NULL (or vice versa), or is all just personal preference?

Edit: I should add (and meant to originally say) that with RAII and exceptions, I rarely use zero/NULL pointers, but sometimes you do need them still.

2

21 Answers 21

201

Here's Stroustrup's take on this: C++ Style and Technique FAQ

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.

That said, don't sweat the small stuff.

1
  • 9
    Bjarne wrote this before C++ 0x started working on a new null type. It will be the case that NULL will be used for this type when it is available for a platform, and I think you'll see a C-change in the general consensus about this. Oct 7, 2008 at 9:49
127

There are a few arguments (one of which is relatively recent) which I believe contradict Bjarne's position on this.

  1. Documentation of intent

    Using NULL allows for searches on its use and it also highlights that the developer wanted to use a NULL pointer, irrespective of whether it is being interpreted by the compiler as NULL or not.

  2. Overload of pointer and 'int' is relatively rare

    The example that everybody quotes is:

     void foo(int*);
     void foo (int);
    
     void bar() {
       foo (NULL);  // Calls 'foo(int)'
     }
    

    However, at least in my opinion, the problem with the above is not that we're using NULL for the null pointer constant: it's that we have overloads of foo() which take very different kinds of arguments. The parameter must be an int too, as any other type will result in an ambiguous call and so generate a helpful compiler warning.

  3. Analysis tools can help TODAY!

    Even in the absence of C++0x, there are tools available today that verify that NULL is being used for pointers, and that 0 is being used for integral types.

  4. C++ 11 will have a new std::nullptr_t type.

    This is the newest argument to the table. The problem of 0 and NULL is being actively addressed for C++0x, and you can guarantee that for every implementation that provides NULL, the very first thing that they will do is:

     #define NULL  nullptr
    

    For those who use NULL rather than 0, the change will be an improvement in type-safety with little or no effort - if anything it may also catch a few bugs where they've used NULL for 0. For anybody using 0 today... well, hopefully they have a good knowledge of regular expressions...

8
  • 1
    Those are some rather good points, I must admit. I am glad that C++ 0x will have a null type, I think that will make a lot of stuff cleaner.
    – Rob
    Oct 7, 2008 at 14:02
  • 2
    @Richard, why not do the opposite? You can use Meyers nullptr_t then when 0x gets avaliable you remove the #include and keep in the safe side all the way. Nov 15, 2009 at 9:18
  • 17
    #define NULL nullptr seems hazardous. For better or worse, lots of legacy code uses NULL for things other than 0. For example, handles are often implemented as some integral type, and setting them to NULL is not uncommon. I've even seen abuses like using NULL to set a char to a zero-terminator. May 1, 2012 at 22:41
  • 8
    @AdrianMcCarthy: I would only say it was hazardous if there was a danger of the code silently compiling and having a different meaning. I'm pretty sure that this isn't the case, so in fact all the incorrect uses of NULL would be detected. May 2, 2012 at 14:40
  • 3
    @RichardCorden: Um, that assumes that those other uses of NULL are actually incorrect. Many APIs have long used NULL with handles, and that is in fact the documented usage with many of them. It's not pragmatic to suddenly break those and declare that they're doing it wrong. May 3, 2012 at 22:41
47

Use NULL. NULL shows your intent. That it is 0 is an implementation detail that should not matter.

6
  • 29
    0 is not an implementation detail. The standard defines 0 to be whatever bit pattern represents a null pointer.
    – Ferruccio
    Dec 10, 2008 at 21:01
  • 5
    As if ..!! Dude, C++ is a low level language! Use 0, it's a well known idiom.
    – hasen
    Mar 30, 2009 at 3:20
  • 11
    I understand that it is a part of the standard. It is an implementation detail as far as reading the code goes. The reader should think "NULL pointer" not "0 which in this case means NULL pointer, not a number I could be doing arithmetic with." Mar 14, 2013 at 20:56
  • 5
    +1. Agreed with Andy. @Ferruccio, Implementation detail of programmer's idea is not the same as compiler's implementation defined
    – user
    Feb 15, 2014 at 23:08
  • if you use NULL, in a plain code without complex header, you will find the error of "NULL is not defined in this scope".. Nov 12, 2017 at 23:07
47

I always use:

  • NULL for pointers
  • '\0' for chars
  • 0.0 for floats and doubles

where 0 would do fine. It is a matter of signaling intent. That said, I am not anal about it.

1
  • 27
    ya probably should use 0.0F for floats, to avoid the implicit typecast
    – EvilTeach
    Oct 8, 2008 at 1:03
34

I stopped using NULL in favor of 0 long ago (as well as as most other macros). I did this not only because I wanted to avoid macros as much as possible, but also because NULL seems to have become over-used in C and C++ code. It seems to be used whenever a 0 value is needed, not just for pointers.

On new projects, I put this in a project header:

static const int nullptr = 0;

Now, when C++0x compliant compilers arrive, all I have to do is remove that line. A nice benefit of this is that Visual Studio already recognizes nullptr as a keyword and highlights it appropriately.

4
  • 4
    Using NULL will be more portable long term. 'nullptr' will be available for some platforms and not for others. Your solution here requires that you use the preprocessor around your declaration to ensure that it's only present when required. NULL will do this automatically. Oct 7, 2008 at 11:28
  • 6
    I disagree. It will be less portable in the short term until compilers catch up. Long term, it will be just as portable and maybe a little more readable.
    – Ferruccio
    Oct 7, 2008 at 14:37
  • 4
    Plus you can always #define nullptr NULL for your non-C++0x compiler.
    – Anteru
    Dec 12, 2009 at 13:16
  • I agree that NULL is overused, I've seen it used to refer to the zero terminator character in a string! I don't think that justifies avoiding it entirely though. Jul 22, 2020 at 13:59
23
    cerr << sizeof(0) << endl;
    cerr << sizeof(NULL) << endl;
    cerr << sizeof(void*) << endl;

    ============
    On a 64-bit gcc RHEL platform you get:
    4
    8
    8
    ================

The moral of the story. You should use NULL when you're dealing with pointers.

1) It declares your intent (don't make me search through all your code trying to figure out if a variable is a pointer or some numeric type).

2) In certain API calls that expect variable arguments, they'll use a NULL-pointer to indicate the end of the argument list. In this case, using a '0' instead of NULL can cause problems. On a 64-bit platform, the va_arg call wants a 64-bit pointer, yet you'll be passing only a 32-bit integer. Seems to me like you're relying on the other 32-bits to be zeroed out for you? I've seen certain compilers (e.g. Intel's icpc) that aren't so gracious -- and this has resulted in runtime errors.

4
  • 1
    NULL perhaps is not portable, and not safe. There might be platforms that still #define NULL 0 (according to Stroustrup's FAQ: Should I use NULL or 0? quoted by the top question and it is among the first search results). At least in older C++, 0 has a special conceptual meaning in pointer context. You should not think concretely about bits. Also note that in different integer contexts (short, int, long long) "sizeof(0)" will be different. I think this answer is a little bit misguided.
    – FooF
    Mar 7, 2014 at 2:42
  • (Personally as a C programmer in daily life, I came to visit this question to understand why people want to use NULL instead of (char *)0, (const char *)0 or (struct Boo *)0 or (void *)0 or whatever to expresses the intent more clearly - without being (in my opinion) too cumbersome.)
    – FooF
    Mar 7, 2014 at 2:51
  • 1
    Vote up. it's happening at msvc2013 C compiler. in 64bit, 0 when convert to a pointer is not guarantee to be NULL Pointer.
    – pengMiao
    Aug 19, 2019 at 17:28
  • NULL is well defined in the standard, so it is absolutely portable. but using NULL is more clear, and after you upgrade to C++11, you can search and replace NULL to be nullptr easily, but for 0, how can you do for it?
    – chen3feng
    Jul 22, 2020 at 4:26
17

If I recall correctly NULL is defined differently in the headers that I have used. For C it is defined as (void*)0, and for C++ it's defines as just 0. The code looked something like:

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

Personally I still use the NULL value to represent null pointers, it makes it explicit that you're using a pointer rather than some integral type. Yes internally the NULL value is still 0 but it isn't represented as such.

Additionally I don't rely on the automatic conversion of integers to boolean values but explicitly compare them.

For example prefer to use:

if (pointer_value != NULL || integer_value == 0)

rather than:

if (pointer_value || !integer_value)

Suffice to say that this is all remedied in C++11 where one can simply use nullptr instead of NULL, and also nullptr_t that is the type of a nullptr.

16

I would say history has spoken and those who argued in favour of using 0 (zero) were wrong (including Bjarne Stroustrup). The arguments in favour of 0 were mostly aesthetics and "personal preference".

After the creation of C++11, with its new nullptr type, some compilers have started complaining (with default parameters) about passing 0 to functions with pointer arguments, because 0 is not a pointer.

If the code had been written using NULL, a simple search and replace could have been performed through the codebase to make it nullptr instead. If you are stuck with code written using the choice of 0 as a pointer it is far more tedious to update it.

And if you have to write new code right now to the C++03 standard (and can't use nullptr), you really should just use NULL. It'll make it much easier for you to update in the future.

1
  • Bjarne Stroustrup prefers using 0 just because he doesn't like macro but also doesn't want to introduce a new keyword. the history proves he was wrong.
    – chen3feng
    Jul 22, 2020 at 4:34
11

I usually use 0. I don't like macros, and there's no guarantee that some third party header you're using doesn't redefine NULL to be something odd.

You could use a nullptr object as proposed by Scott Meyers and others until C++ gets a nullptr keyword:

const // It is a const object...
class nullptr_t 
{
public:
    template<class T>
    operator T*() const // convertible to any type of null non-member pointer...
    { return 0; }

    template<class C, class T>
    operator T C::*() const   // or any type of null member pointer...
    { return 0; }

private:
    void operator&() const;  // Can't take address of nullptr

} nullptr = {};

Google "nullptr" for more info.

7
  • 11
    Any third-party library that defines NULL to anything other than 0 (or (void*)0 if being compiled as C code) is just asking for trouble and should not be used. Aug 5, 2009 at 19:07
  • 3
    Have you ever actually seen a library that redefines NULL? Ever? If such a library ever existed, you'd have bigger problems than the redefined NULL, such as that you're using a library that is dumb enough to redefine NULL. Apr 2, 2013 at 3:10
  • 1
    Well over a decade ago I vaguely remember having to deal with some 3rd-party headers, possibly either Orbix or ObjectStore, that did define NULL. I think I have a pathological hatred of macros after wasting several days and nights trying to get various 3rd-party headers to work with windows.h.
    – jon hanson
    Apr 4, 2013 at 20:18
  • 3
    "don't like macros" is an odd critique of an object-like #define. Maybe you mean to say that you don't like the C-preprocessor? Feb 12, 2014 at 16:40
  • 1
    Redefining standard macros is undefined behavior iirc. Feb 1, 2020 at 16:28
11

I once worked on a machine where 0 was a valid address and NULL was defined as a special octal value. On that machine (0 != NULL), so code such as

char *p;

...

if (p) { ... }

would not work as you expect. You HAD to write

if (p != NULL) { ... }

Although I believe most compilers define NULL as 0 these days I still remember the lesson from those years ago: NULL is not necessarily 0.

4
  • 28
    You were not using a compliant compiler. The standard says NULL is 0 and that the compiler should convert 0 in a pointer context into a proper true NULL value for the arch.
    – Evan Teran
    Oct 7, 2008 at 2:40
  • 17
    Yes, you are right. This was in mid-80s before ANSI produced a C standard. There was no such thing as compliance then and compiler writers were free to interpret the language as they saw fit. That's why a standard was necessary.
    – mxg
    Oct 8, 2008 at 22:42
  • @EvanTeran This isn't true for C. (void *)0 must compare equal to NULL, but it doesn't actually have to be 0. Some people have argued that NULL should be 0xffffffff... or 0xf7ffffff... since 0x00 may be a valid address, but so far, most implementations use NULL = 0.
    – yyny
    Jul 31, 2020 at 15:09
  • @yyny you are mistaken. There is a difference between the "null constant" and the "null value". The null constant is BY DEFINITION, 0 according to the standard, this is what you write in your code. However, the compiler may choose to emit a different VALUE for the null constant in the resultant machine code. In other words, when you write p = 0; (where p is a pointer), the compiler will see the 0 as the null constant. But when emitting the instruction to store "null", will store the machine-specific null value which may or may not be literally the address 0x0.
    – Evan Teran
    Sep 10, 2020 at 4:12
10

I think the standard guarantees that NULL == 0, so you can do either. I prefer NULL because it documents your intent.

1
  • If you have nested structures, I think saying foo.bar_ptr = (Bar *) 0 expresses the intent much clearer than foo.bar_ptr = NULL. This habit also empowers the compiler to catch misconception errors for you. For me, foo.bar_ptr = 0 expresses the intent as well as using NULL if I know that foo.bar_ptr is a pointer.
    – FooF
    Mar 7, 2014 at 3:13
10

Using either 0 or NULL will have the same effect.

However, that doesn't mean that they are both good programming practices. Given that there is no difference in performance, choosing a low-level-aware option over an agnostic/abstract alternative is a bad programming practice. Help readers of your code understand your thought process.

NULL, 0, 0.0, '\0', 0x00 and whatelse all translate to the same thing, but are different logical entities in your program. They should be used as such. NULL is a pointer, 0 is quantity, 0x0 is a value whose bits are interesting etc. You wouldn't assign '\0' to a pointer whether it compiles or not.

I know some communities encourage demonstrating in-depth knowledge of an environment by breaking the environment's contracts. Responsible programmers, however, make maintainable code and keep such practices out of their code.

0
6

Strange, nobody, including Stroustroup mentioned that. While talking a lot about standards and aesthetics nobody noticed that it is dangerous to use 0 in NULL's stead, for instance, in variable argument list on the architecture where sizeof(int) != sizeof(void*). Like Stroustroup, I prefer 0 for aesthetic reasons, but one has to be careful not to use it where its type might be ambiguous.

9
  • And in those dangerous places you can still use 0 provided you specify which 0 you mean -- for example (int *)0, (char *)0, (const char *)0 or (void *)0 or (unsigned long long) 0 or whatever. This in my opinion expresses the intent much clearer than NULL.
    – FooF
    Mar 6, 2014 at 10:17
  • 1
    Sure, if you don't know what NULL stands for. Mar 6, 2014 at 14:55
  • I personally find it a little bit distasteful to needlessly cast something to (void *) when I could use the exact type. I purposefully gave example of (typically) 64-bit integer in the list because it is analogous to the pointer case. Furthermore, if my recollection that older C++ defined NULL as 0 is accurate (it is years since I programmed in C++), then we witness no improvement in program correctness. Newer C++ standard fortunately provides nullptr keyword, so we can get rid of this NULL uglity and the whole controversy when writing newer C++.
    – FooF
    Mar 6, 2014 at 15:16
  • Well, that's why casting to (void*) has been abstracted to NULL. And NULL actually does express the intent quite clearly most of the time. And I think your recollection is wrong. Not sure about standards, but in practice I believe it's been (void*)0. And yess, nullptr is a nice prettifier, though it amounts to the same NULL thing — specifying null-pointer without specifying type. Mar 6, 2014 at 16:56
  • 1
    @FooF, on some platforms — maybe. In my reality it worked and therefore I suspect it's been defined as a pointer. As for robustness, yes, what I was trying to say that using nullptr bears the same message as NULL, that was only regarding expressing the intent you mentioned in the very beginning. (Preprocessing NULL on modern gcc yields __null, whatever it is). Mar 7, 2014 at 8:40
4

I try to avoid the whole question by using C++ references where possible. Rather than

void foo(const Bar* pBar) { ... }

you might often be able to write

void foo(const Bar& bar) { ... }

Of course, this doesn't always work; but null pointers can be overused.

3

I'm with Stroustrup on this one :-) Since NULL is not part of the language, I prefer to use 0.

3

Mostly personal preference, though one could make the argument that NULL makes it quite obvious that the object is a pointer which currently doesn't point to anything, e.g.

void *ptr = &something;
/* lots o' code */
ptr = NULL; // more obvious that it's a pointer and not being used

IIRC, the standard does not require NULL to be 0, so using whatever is defined in <stddef.h> is probably best for your compiler.

Another facet to the argument is whether you should use logical comparisons (implicit cast to bool) or explicity check against NULL, but that comes down to readability as well.

3

I prefer to use NULL as it makes clear that your intent is the value represents a pointer not an arithmetic value. The fact that it's a macro is unfortunate, but since it's so widely ingrained there's little danger (unless someone does something really boneheaded). I do wish it were a keyword from the beginning, but what can you do?

That said, I have no problem with using pointers as truth values in themselves. Just as with NULL, it's an ingrained idiom.

C++09 will add the the nullptr construct which I think is long overdue.

1

I always use 0. Not for any real thought out reason, just because when I was first learning C++ I read something that recommended using 0 and I've just always done it that way. In theory there could be a confusion issue in readability but in practice I have never once come across such an issue in thousands of man-hours and millions of lines of code. As Stroustrup says, it's really just a personal aesthetic issue until the standard becomes nullptr.

1

Someone told me once... I am going to redefine NULL to 69. Since then I don't use it :P

It makes your code quite vulnerable.

Edit:

Not everything in the standard is perfect. The macro NULL is an implementation-defined C++ null pointer constant not fully compatible with C NULL macro, what besides the type hiding implicit convert it in a useless and prone to errors tool.

NULL does not behaves as a null pointer but as a O/OL literal.

Tell me next example is not confusing:

void foo(char *); 
void foo(int); 
foo(NULL); // calls int version instead of pointer version! 

Is because of all that, in the new standard appears std::nullptr_t

If you don't want to wait for the new standard and want to use a nullptr, use at least a decent one like the proposed by Meyers (see jon.h comment).

1
  • 5
    NULL is a well defined part of the C++ standard. Letting people who like to redefine standard macros edit code in your project makes your code 'vulnerable'; using NULL doesn't.
    – CB Bailey
    Aug 5, 2009 at 16:41
1

Well I argue for not using 0 or NULL pointers at all whenever possible.

Using them will sooner or later lead to segmentation faults in your code. In my experience this, and pointers in gereral is one of the biggest source of bugs in C++

also, it leads to "if-not-null" statements all over your code. Much nicer if you can rely on always a valid state.

There is almost always a better alternative.

1
  • 2
    A guaranteed segmentation fault (and it is guaranteed on modern systems when you dereference 0) is useful for debugging. Much better than dereferencing random garbage and getting who knows what result. Jul 10, 2013 at 9:33
-4

Setting a pointer to 0 is just not that clear. Especially if you come a language other than C++. This includes C as well as Javascript.

I recently delt with some code like so:

virtual void DrawTo(BITMAP *buffer) =0;

for pure virtual function for the first time. I thought it to be some magic jiberjash for a week. When I realized it was just basically setting the function pointer to a null (as virtual functions are just function pointers in most cases for C++) I kicked myself.

virtual void DrawTo(BITMAP *buffer) =null;

would have been less confusing than that basterdation without proper spacing to my new eyes. Actually, I am wondering why C++ doesn't employ lowercase null much like it employes lowercase false and true now.

2
  • In general I prefer NULl to 0 for pointers. However '= 0;' is the idiomatic way to declare a pure virtual function in C++. I would strongly advise you don't use '= NULL;' for this particular case.
    – danio
    Jan 10, 2012 at 10:37
  • This is the most funny comment on StackOverflow. You probably already know now that the example you gave is a syntax for pure virtual function and not a pointer. And yes @danio is right, you should not use NULL for pure virtual function.
    – sgowd
    Jan 19, 2017 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.