C语言 定义 NULL 和 NULL_POINTER 的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18781514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:26:19  来源:igfitidea点击:

Correct way of defining NULL and NULL_POINTER?

cpointersnullc-preprocessor

提问by Niklas

As far as I know, Cdefines NULLlike this:

据我所知,C定义NULL如下:

#define NULL ( (void *) 0)

Then, how should we define NULL_POINTER? I defined it the same in my program and it worked, but I suppose that is just a coincidence:

那么,我们应该如何定义NULL_POINTER?我在我的程序中对其进行了相同的定义并且它起作用了,但我认为这只是巧合:

#define NULL_POINTER ( (void *) 0)

What would be the logical definition, if any ?

如果有的话,逻辑定义是什么?

回答by Yu Hao

#define NULL ( (void *) 0)

and

#define NULL 0

are both valid. If you need to implement your own macro for null pointer, the same rule applies.

都是有效的。如果您需要为空指针实现自己的宏,则适用相同的规则。

C11(ISO/IEC 9899:201x) §6.3.2.3 PointersSection 3

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

C11(ISO/IEC 9899:201x) §6.3.2.3指针第 3 节

带有值的整数常量表达式0,或转换为类型的此类表达式 void *,称为空指针常量。

回答by Dayal rai

It is only in pointer contexts that NULLand 0are equivalent. NULLshould not be used when another kind of 0is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULLto be ((void *)0), which will not work at all in non-pointer contexts.) In particular, do not use NULLwhen the ASCII null character (NUL) is desired. Provide your own definition

只有在指针上下文中NULL0是等价的。NULL不应在需要另一种类型时0使用,即使它可能有效,因为这样做会发送错误的风格信息。(此外,ANSI允许的定义NULL((void *)0),这将在所有的在非指针上下文不工作。)特别是,不使用NULL该ASCII空字符(NUL)期望时。提供您自己的定义

#define NUL '##代码##'

NULLshould be used only as a pointer constant.

NULL应仅用作指针常量。