I am writing some header files that will be included by C++ code and also included by C code. I would prefer for the header source code to be consistent and always use "nullptr" rather than NULL (or the integer constant 0) in these headers.
This brings up the possibility of adding a piece of code such as:
#ifndef __cplusplus
#define nullptr 0 /* or ((void *)0) */
#endif
Or alternatively:
#include <stdio.h>
#ifndef __cplusplus
#define nullptr NULL
#endif
Edit: Or from Ben Voigt's suggestion:
#ifndef __cplusplus
static const void *nullptr = 0;
#endif
The question is, what is the downside to doing this? Is there some reason why nullptr was added to C++ but not to C? This seems like something that would make code more consistent and readable when C++ and C have to inter-operate.
Edit: a sample header
#ifdef __cplusplus
extern "C" {
#endif
extern struct MyStruct *globalMyStruct;
extern int myFunc(struct MyStruct *ptr,int arg);
#ifdef __cplusplus
}
#endif
#define MYMACRO(x) ((globalMyStruct!=nullptr) ? myFunc(globalMyStruct,(x)) : -1)
Even if MyStruct is a C++ object, then it is legal for C code to include the above header file and use the MYMACRO definition. I want to include the above header code in both C and C++ files. But if I include the above header from a C file, then it won't compile due to the use of nullptr.
It is perfectly valid for C code to contain pointers to C++ objects, and those pointers can be passed as arguments to functions (and perhaps those functions are written in C++). This is just one way C++ and C can inter-operate.