为NULL /假的C和C ++什么比为0x0 / 0B0 /'\\ 0'/ 0更多 [英] is NULL/false in C and C++ anything more than 0x0 / 0b0 / '\0' / 0

查看:148
本文介绍了为NULL /假的C和C ++什么比为0x0 / 0B0 /'\\ 0'/ 0更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于在问题中提到,我一直在使用NULL和假(在C ++)交替使用0或0x0和等。我很好奇,知道他们是否持有比做0同义词以外的任何特殊含义。

As mentioned in the question, I have been using NULL and false(in C++) interchangeably with 0 or 0x0 and so on. I was curious to know if they held any special meaning other than being synonyms of 0.

推荐答案

一些平台 NULL 不是为0x0

NULL在C语言所需/定义为零?:

NULL 保证是零,也许铸造到(无效*) 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 ,或者这样的前pression投整型常量前pression键入
  无效* ,被称为空指针常量。(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定义在< STDDEF.H方式> (和其他标题)作为空指针常量

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

注意,因为如何空指针的规则制定,您使用值来分配/比较空指针保证是零,但实际上存储在里面的指针的位模式可以是任何其他东西(但据我所知只有少数非常深奥的平台,利用这个事实,而这不应该是一个问题,因为无论如何看到你应该进入的 UB -land反正)。

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 ); 如果(!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.

话虽这么说,我平时写明确如果(PTR == NULL)而不是如果(!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 ++中的无效* 投不能present由于严格的隐式转换规则会使得这种使用 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).

这篇关于为NULL /假的C和C ++什么比为0x0 / 0B0 /'\\ 0'/ 0更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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