C 中的 NULL 是否需要/定义为零? [英] Is NULL in C required/defined to be zero?

查看:17
本文介绍了C 中的 NULL 是否需要/定义为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NULL 在我的 GCC 测试程序中似乎为零,但维基百科说 NULL 只需要指向不可寻址的内存.

NULL appears to be zero in my GCC test programs, but wikipedia says that NULL is only required to point to unaddressable memory.

是否有任何编译器使 NULL 非零?我很好奇 if (ptr == NULL) 是否比 if (!ptr) 更好.

Do any compilers make NULL non-zero? I'm curious whether if (ptr == NULL) is better practice than if (!ptr).

推荐答案

NULL 保证为零,可能被强制转换为 (void *)1.

NULL is guaranteed to be zero, perhaps casted to (void *)1.

C99,§6.3.2.3,¶3

C99, §6.3.2.3, ¶3

值为 0 的整数常量表达式,或这样的表达式转换为类型void *,称为空指针常量.(55) 如果将空指针常量转换为指针类型,结果指针,称为空指针,保证比较不相等指向任何对象或函数的指针.

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.(55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

注释 55 说:

55) 宏 NULL 在 (和其他头文件)中定义为空指针常量.

55) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant.

请注意,由于空指针的规则是如何制定的,用于分配/比较空指针的值保证为零,但实际存储在指针内的位模式可以是任何其他东西(但AFAIK只有少数非常深奥的平台利用了这一事实,无论如何这应该不是问题,因为要查看"底层位模式,您应该进入 UB - 无论如何都要降落).

Notice that, because of how the rules for null pointers are formulated, the value you use to assign/compare null pointers is guaranteed to be zero, but the bit pattern actually stored inside the pointer can be any other thing (but AFAIK only few very esoteric platforms exploited this fact, and this should not be a problem anyway since to "see" the underlying bit pattern you should go into UB-land anyway).

所以,就标准而言,这两种形式是等价的(!ptr 等价于 ptr==0 由于 §6.5.3.3 ¶5, 而 ptr==0 等价于 ptr==NULL);if(!ptr) 也很地道.

So, as far as the standard is concerned, the two forms are equivalent (!ptr is equivalent to ptr==0 due to §6.5.3.3 ¶5, and ptr==0 is equivalent to ptr==NULL); if(!ptr) is also quite idiomatic.

话虽如此,我通常会明确写出 if(ptr==NULL) 而不是 if(!ptr) 以明确我正在检查空指针而不是一些布尔值.

That being said, I usually write explicitly if(ptr==NULL) instead of if(!ptr) to make it extra clear that I'm checking a pointer for nullity instead of some boolean value.

  1. 请注意,在 C++ 中,void * 转换不能存在,因为更严格的隐式转换规则会使这种 NULL 的使用变得麻烦(您必须明确地每次都将其转换为比较指针的类型).
  1. Notice that in C++ the void * cast cannot be present due to the stricter implicit casting rules that would make the usage of such NULL cumbersome (you would have to explicitly convert it to the compared pointer's type every time).

这篇关于C 中的 NULL 是否需要/定义为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆