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

标签 c language-lawyer

以下 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/

相关文章:

c - 如何让C程序发出HTTP请求并读取响应?

c - 匿名字符串文字效率低下吗?

c - 是否有任何关于 __LINE__ 指令一致性的保证?

c++ - 作为抽象,C++ 是否支持 "bits"表示两个以上值之一?

将 char 数组转换为一个 int

从现有的 x 宏创建相关的 x 宏

c - 在 C 中使用 crypt 进行简单密码比较

c++ - 将变量用作 emplace_back 的参数后可以使用变量吗?

c++ - 推导指南中的引用和值之间的差异

c - 自动将结构成员初始化为 NULL