Subtraction of two nullptr values guaranteed to be zero?

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

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)

The simplest code example I can think of being:

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

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?

回答1:

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

5.7 Additive operators [expr.add]

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!