PDA

View Full Version : Pointers: NULL vs. 0



hackerNovitiate
31st January 2010, 14:38
Hi, I noticed that Trolltech's code examples use 0 instead of NULL to represent null pointers. Does it matter which one I use?

franz
31st January 2010, 14:43
No it doesn't matter. A pointer is in the end just an integer. The null pointer can either be:


#define NULL 0

or


#define NULL ((void *)0)


More often than not, the former is used.

In the C++0x standard that is still in the making, plans are to deprecate the above definitions and introduce a null pointer called nullptr_t, to prevent the following confusion:


void func(int i);
void func(const char *t);

wysota
31st January 2010, 15:47
You shouldn't (or at least needn't) use NULL in C++ code. NULL is a C macro while C++ has "null" and "0" defined, you should use either of them.

hackerNovitiate
1st February 2010, 14:51
You shouldn't (or at least needn't) use NULL in C++ code. NULL is a C macro while C++ has "null" and "0" defined, you should use either of them.

I tried to compile
int *p = null; but g++ reported "error: 'null' was not in this scope". Do I need to #include something?

Also, I was directed to Bjarne Stroustrup's (creator of C++) website at http://www2.research.att.com/~bs/bs_faq2.html#null where he said "In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0" which sounds like NULL is ok in C++...?

Sorry for posting in the wrong forum; I thought it was Qt thing instead of a C++ thing.

wysota
1st February 2010, 15:50
Hmm... maybe there is no "null"... I though there was but maybe it was just a macro to 0.

NULL is ok as it is most often defined as "0". But NULL in C is theoretically "0L" which makes a difference in length. But there is no practical difference, apart from aesthetics - if you get paid by the character, it's better to write "NULL", it's three chars longer ;)

kuzulis
1st February 2010, 16:08
Hi, I noticed that Trolltech's code examples use 0 instead of NULL to represent null pointers. Does it matter which one I use?

Use 0 .

pitonyak
2nd February 2010, 16:20
Stroustrup prefers that you use 0 rather than NULL, because in C++ it is defined as 0 and he prefers to NOT use macros.

http://www2.research.att.com/~bs/bs_faq2.html#null

The next version of C++ will use a keyword nullptr for this. If you choose to use NULL now, it will be easier to find and replace NULL with nullptr later.