Is it unspecified behavior to compare pointers to different arrays for equality?(比较指向不同数组的指针是否相等是未指定的行为吗?)
问题描述
相等运算符在指针上具有关系运算符的语义限制:
The equality operators have the semantic restrictions of relational operators on pointers:
==(等于)和 !=(不等于)运算符与关系运算符具有相同的语义限制、转换和结果类型,但它们的优先级和真值结果较低.[C++03 §5.10p2]
The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result. [C++03 §5.10p2]
关系运算符对比较指针有限制:
And the relational operators have a restriction on comparing pointers:
如果两个相同类型的指针 p 和 q 指向不同的对象,这些对象不是同一对象的成员或同一数组的元素或不同的函数,或者只有其中一个为空,则 p<q、p>q、p<=q和p>=q是未指定的.[§5.9p2]
If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified. [§5.9p2]
这是由等式运算符继承"的语义限制吗?
Is this a semantic restriction which is "inherited" by equality operators?
具体来说,给定:
int a[42];
int b[42];
很明显 (a + 3) <(b + 3) 是未指定的,但是 (a + 3) == (b + 3) 也是未指定的吗?
It is clear that (a + 3) < (b + 3) is unspecified, but is (a + 3) == (b + 3) also unspecified?
推荐答案
op==
和 op!=
的语义明确表示映射是 除了他们的真值结果.因此,您需要查看为它们的真值结果定义了什么.如果他们说结果未指定,那么它就是未指定的.如果他们定义了特定的规则,那就不是.它特别说
The semantics for op==
and op!=
explicitly say that the mapping is except for their truth-value result. So you need to look what is defined for their truth value result. If they say that the result is unspecified, then it is unspecified. If they define specific rules, then it is not. It says in particular
相同类型的两个指针比较相等当且仅当它们都为空,都指向同一个函数,或者都代表同一个地址
Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address
这篇关于比较指向不同数组的指针是否相等是未指定的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较指向不同数组的指针是否相等是未指定的行


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01