两个nullptr值相减保证为零

两个nullptr值相减保证为零

本文介绍了两个nullptr值相减保证为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个相同类型的指针的值等于nullptr,那么C ++标准是否保证这些指针之间的差等于0?

Is it guaranteed by the C++ standard that if I have two pointers of the same type whose value is equal to nullptr, that the difference between those pointers is equal to 0?

用伪数学符号表示,以下谓词是否成立?

In a pseudo-mathematical notation, does the following predicate hold true?

ForAll x ForAll y(x == nullptr)^(y == nullptr)- >(x-y == 0)

ForAll x ForAll y (x == nullptr)^(y == nullptr) -> (x - y == 0)

我能想到的最简单的代码示例是:

The simplest code example I can think of being:

int* x = nullptr;
int* y = nullptr;
assert(x - y == 0);

我想这可以归结为:是否有可能有效地实现C ++标准,是的,nullptr有多个位表示形式只能比较为相等,因为相等运算符确实具有某些魔力?

I suppose this boils down to: is it possible to have a valid implementation of the C++ standard for which there are multiple bit representations of nullptr that only compare as being equal because the equality operator does some magic?

推荐答案

是的,即有效。它在C中是未定义的,但是C ++在-运算符中添加了一个特殊的异常来定义行为。

Yes, that is valid. It would be undefined in C, but C++ has added a special exception to the - operator to define the behaviour.

7如果添加了值 0 从指针值减去或从指针值减去后,结果比较等于原始指针值。如果两个指针指向同一对象,或者两个指针都指向同一数组的末尾,或者两个指针都为空,并且两个指针相减,则结果等于值 0 转换为类型 std :: ptrdiff_t

7 If the value 0 is added to or subtracted from a pointer value, the result compares equal to the original pointer value. If two pointers point to the same object or both point one past the end of the same array or both are null, and the two pointers are subtracted, the result compares equal to the value 0 converted to the type std::ptrdiff_t.

这篇关于两个nullptr值相减保证为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:35