Question about NULL

Started by
14 comments, last by counterrabbit 18 years, 6 months ago
If NULL is defined as 0 would it be wrong to set pointers to 0 instead of NULL?
Advertisement
No:

#define NULL 0
char* tempPtr = NULL;

The line: char* tempPtr = NULL; is then char* tempPtr = 0; after the preprocessor substitues in 0 for NULL. The point of the define is to remap one symbol/expression into something else. In this case, NULL and 0 are the same thing.
Quote:Original post by FlyingDemon
If NULL is defined as 0 would it be wrong to set pointers to 0 instead of NULL?


It isn't necessarily *wrong* it's just the same thing.
Quote:Original post by Drew_Benton
No:

#define NULL 0
char* tempPtr = NULL;

The line: char* tempPtr = NULL; is then char* tempPtr = 0; after the preprocessor substitues in 0 for NULL. The point of the define is to remap one symbol/expression into something else. In this case, NULL and 0 are the same thing.


Actually in C, NULL is defined as :

#define NULL (void*)0


In c++ it's basically 0.
NULL is just absence of a value. I know that in Java, NULL is actually infact, absent of a value. In C/C++ you just have to settle with 0 really, although if the implementation changed (for whatever daft reason), you could just redefine NULL to be the real implementation of NULL.
Adventures of a Pro & Hobby Games Programmer - http://neilo-gd.blogspot.com/Twitter - http://twitter.com/neilogd
Ok. I was just woundering because everytime I needed to use NULL I had to include a header that defined it like stdlib or define it myself.
Quote:Original post by FlyingDemon
Ok. I was just woundering because everytime I needed to use NULL I had to include a header that defined it like stdlib or define it myself.


Well NULL is also just a convention to use, so don't include more header files just to get that. Are you using NULL for any reason in particular?
Quote:Original post by FlyingDemon
Ok. I was just woundering because everytime I needed to use NULL I had to include a header that defined it like stdlib or define it myself.
stddef.h is the standard header if you only need NULL (or size_t/ptrdiff_t/offsetof).

Additionally GCC checks for use of NULL in non-pointers contexts so it basically acts the same way as a (void *) 0 definition would in C, but with warnings instead of errors as the result of any abuse.

It's mostly a matter of style/taste however. So if you're uncomfortable with having to include it or just think 0 looks better then feel free to switch.
Personally I prefer to use NULL.
I'm only using NULL to set pointers to NULL after they no longer point to other things, and after de-allocating memory.
I still prefer Scott Meyer's* Templatized-Null-On-Crack™.

Enigma

*It may well not be his invention, but it was his book which introduced me to the concept.

This topic is closed to new replies.

Advertisement