Null pointers in C++

EvilManagedCare

Senior member
Nov 6, 2004
324
0
0
Are these methods synonymous when declaring null pointers in C++?

e.g. int * p = NULL and int *p = 0

I thought they were, but wanted to confirm. Thanks in advance.
 

Sc4freak

Guest
Oct 22, 2004
953
0
0
Yes, they are. NULL is guaranteed to be #define'd as the integer constant 0 (or something similar).

The integer constant 0 is "special" in the context of pointers, as it is known as the null pointer constant. Assigning a null pointer constant to a pointer is guaranteed to produce a null pointer. Comparing a pointer to the null pointer constant returns true if the pointer is a null pointer. However, the specific bit pattern of a null pointer is not guaranteed to be the same as the integer constant 0 (the null pointer constant).
 

brandonb

Diamond Member
Oct 17, 2006
3,731
2
0
Somewhere in the big sea of header files, you will find this:

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

The #define statement replaces that keyword with the value, so when you compile your code all "NULL" keywords just turn into 0's.

So yes, it will be the same. But it all depends on what headers are included into your project.

Edit: Wow I'm too slow, by 5 minutes. heh
 

Madwand1

Diamond Member
Jan 23, 2006
3,309
0
76

If you have to name the null pointer, call it nullptr; that's what it's going to be called in C++0x. Then, "nullptr" will be a keyword.

I like 0 just fine, and it's ubiquitous to the point where the term "0 pointer", etc., are in some cases more common than "null", so at first encounter didn't like "nullptr" much. However, as a type-safe construct, it has some utility in that with it the compiler can catch some common parameter mismatch errors.
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
I like 0 just fine, and it's ubiquitous to the point where the term "0 pointer", etc., are in some cases more common than "null", so at first encounter didn't like "nullptr" much. However, as a type-safe construct, it has some utility in that with it the compiler can catch some common parameter mismatch errors.

I don't really like the term nullptr myself, I was just linking to that as confirmation that you can be sure that NULL is always 0 in standard C++ which I don't think was the case in C and pre-standard C++.