在新版《GCC》中,不同出处的指针可以等同:
// test.c
#include <stdio.h>
int a[4];
int b[4];
int main() {
puts(a+4 == b ? "equal" : "inequal");
return 0;
}
$ gcc --version
gcc (GCC) 13.2.1 20230801
$ gcc test.c && ./a.out
equal
此行为是否符合c标准?
在新版《GCC》中,不同出处的指针可以等同:
// test.c
#include <stdio.h>
int a[4];
int b[4];
int main() {
puts(a+4 == b ? "equal" : "inequal");
return 0;
}
$ gcc --version
gcc (GCC) 13.2.1 20230801
$ gcc test.c && ./a.out
equal
此行为是否符合c标准?
这是允许发生的,但不能保证.
第C standard条中关于相等运算符的第6.5.9p6节规定:
Two pointers compare equal if and only if两者都是空指针,都是 是指向同一对象的指针(包括指向对象的指针和 开头的子对象)或函数,两者都是指向一个 经过相同数组对象的最后一个元素,or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.109)
...
- Two objects may be adjacent in memory,因为它们是较大数组的相邻元素,或者 struct 的相邻成员之间没有填充,or because the implementation chose to place them so, even though they are unrelated.如果先前的无效指针操作(如访问 数组边界之外)产生未定义行为,后续比较也会产生未定义行为 行为
一些编译器可能知道指针的出处,并可以使用该知识来决定这种比较是否正确.
另请参阅:Can an equality comparison of unrelated pointers evaluate to true?