gpt4 book ai didi

c - 将硬编码字符串与 == 进行比较的结果

转载 作者:行者123 更新时间:2023-12-04 09:14:59 27 4
gpt4 key购买 nike

以下 C 代码尝试使用 == 比较硬编码字符串:

#include <stdbool.h>

bool test_address_aliasing() {
const char * a = "1";
const char * b = "1";
return a==b;
}

这将比较指向 ab 的指针,并且优化编译器很可能会合并对 ab 的引用 将它们存储在同一个地方,从而导致 a==b 为真。但是,不需要编译器将对等效字符串的引用组合在一起,那么实际结果实现是否已定义? (如果答案取决于 C 规范的版本,我对 C99 最感兴趣。)

最佳答案

不确定两个内容相同的字符串常量是否指向同一个对象。 C11 standard 的第 6.4.5p7 节关于字符串常量状态:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

实际的指针比较在任何一种情况下都是有效的(参见 C11 6.5.9p6 ):

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, 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.

关于c - 将硬编码字符串与 == 进行比较的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com