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.
The downside is defined as the negative aspects or the disadvantages of something. An example of the downside of home ownership is the costs and expenses with home upkeep. noun. The lower side or portion. noun.
Considering the positive, beneficial, advantageous, etc., aspects of a situation, especially one that is or would be otherwise negative, detrimental, or disadvantageous.
Definition of pros and cons 1 : arguments for and against —often + of Congress weighed the pros and cons of the new tax plan. 2 : good points and bad points Each technology has its pros and cons.
Two downsides off the top of my head:
Edit: Something I do in older versions of C++ (but not C):
#if __cplusplus >= 201103L || (__cplusplus < 200000 && __cplusplus > 199711L)
//use C++ 11 nullptr
#else
struct nullptr_t
{
template <class T>
operator T* (){return (T*)0;}
}nullptr;
#endif
It mimicks the behavior of nullptr without being a macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With