本文介绍了两个指针相等等于被转换为整数类型相等吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: 如果比较相等的指针的整数转换值也相等吗?

Question: If pointers comparing equals are their integer-converted values also equal?

例如:

void *ptr1 = //...
void *ptr2 = //...
printf("%d", ptr1 == ptr2); //prints 1

这是否意味着(intptr_t) ptr1 == (intptr_t) ptr2也是1?

从务实的角度来看应该是正确的.但是考虑标准在7.20.1.4(p1)中指定的内容:

From pragmatic point of view that should be right. But considering what the Standard specifies at 7.20.1.4(p1):

    intptr_t

与实现可以将相同的指针转换为不同的值(取决于某些奇怪的情况)并不矛盾,这保留了转换回的值产生相同的指针.

it does not contradict to that an implementation can convert the same pointers to different values (depending on some weird circumstances), preserving that the values converted back yields the same pointers.

所以,我认为不,比较相等的指针的整数转换值不必彼此相等.

So, I think no, the integer-converted values of pointers comparing equal are not necessary equal to each other.

推荐答案

您的分析是正确的.除了允许在§6.3.2.3,该标准未提及该转换应如何进行.当然,在intptr_t上有一个往返"要求,但是它不能阻止一个以上的行程,而编译器会根据某些约束或要求选择一个或另一个行程.

Your analysis is correct. Other than allowing conversions to and from integers at §6.3.2.3, the standard doesn't mention how that conversion should behave. Granted, there is a "round trip" requirement on intptr_t, but it doesn't prevent more than a single trip being possible, with the compiler choosing one or another based on some constraint or requirement.

实际上,C标准不需要(intptr_t) ptr1 == (intptr_t) ptr2即可保存.

So indeed, the C standard doesn't require (intptr_t) ptr1 == (intptr_t) ptr2 to hold.

这篇关于两个指针相等等于被转换为整数类型相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:57