C++ tips

Purpose of this document

Main goal of this page is to give some tips about the C++ langugage.

program version
gcc 3.4.6

About the NULL macro

This tips works around the question of assigning/testing a variable to a null pointer.

The NULL macro is defined in the standard stddef.h file:

/usr/lib/gcc/i386-redhat-linux/3.4.3/include/stddef.h
...
/* A null pointer constant.  */

#if defined (_STDDEF_H) || defined (__need_NULL)
#undef NULL   /* in case  has defined it. */
#ifdef __GNUG__
#define NULL __null
#else   /* G++ */
#ifndef __cplusplus
#define NULL ((void *)0)
#else   /* C++ */
#define NULL 0
#endif  /* C++ */
#endif  /* G++ */
#endif  /* NULL not defined and  or need NULL.  */
#undef  __need_NULL
...

As you see in the C++ case the NULL macro is defined as 0. So there is only an aesthetic difference to use 0 or NULL.

However NULL is a macro it should be miss defined... so it is preferable to use 0: is is explicit and there is no ambiguity.

The next standard version of C++, called C++0x, will define the keyword nullptr to represent a null pointer. So you can also define a macro named nullptr.

Useful links

link comment
Use the GNU Compiler Collection (GCC) the official documentation
Bjarne Stroustrup's C++ Style and Technique FAQ from the creator of the C++