在C代码中使用#Define NullPTR有没有缺点

Is there any downside to having a #define nullptr in C code?

本文关键字:NullPTR 有缺点 #Define 代码      更新时间:2023-10-16

我正在编写一些标题文件,这些文件将由C 代码包含,也包含在C代码中。我希望标题源代码保持一致,并始终使用" nullptr",而不是这些标题中的null(或整数常数0)。

这提出了添加一件代码的可能性,例如:

#ifndef __cplusplus
#define nullptr 0      /* or ((void *)0) */
#endif

或替代:

#include <stdio.h>
#ifndef __cplusplus
#define nullptr NULL
#endif

编辑:或来自Ben Voigt的建议:

#ifndef __cplusplus
static const void *nullptr = 0;
#endif

问题是,这样做的缺点是什么?是否有一些理由将NULLPTR添加到C 而不将其添加到C中?当C 和C必须互操作时,这似乎可以使代码更加一致和可读。

编辑:示例标头

#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)

即使my -struct是C 对象,也可以包含上述标头文件并使用mymacro定义是合法的。我想在C和C 文件中包括上述标头代码。但是,如果我从c文件中包括上述标头,则由于使用nullptr。

对于C代码,将指针包含到C 对象是完全有效的,并且可以将这些指针作为参数传递给函数(也许这些功能是用C 编写的)。这只是C 的一种方式,C可以连接。

我头顶上的两个缺点:

  • null/0和nullptr具有不同的行为(如下所述),您不希望nullptr(macro)和nullptr(语言功能)具有不同的行为,即使它们看起来相同,您会吗?
  • 应避免宏(无论如何,在C中尽可能多...)

编辑:我在较旧版本的C (但不是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

它模仿nullptr的行为而不是宏。