c++ - 将字符数组 char u[10] 与字符串文字 "abc"进行比较是否是未定义的行为

我遇到了 this关于 SO 的问题,以及 this回答问题。代码如下:

int main()
{

    char u[10];
    cout<<"Enter shape name ";
    cin>>u;
    if(u=="tri") //IS THIS UNDEFINED BEHAVIOR because the two decayed pointers both point to unrelated objects?
    {
        cout<<"everything is fine";
    }
    else
    {
        cout<<"Not fine";
    }
    return 0;
}

我在提到的答案中读到,u"tri" 都会衰减到指向其第一个元素的指针。我的问题是,现在正在比较这两个衰减的指针 undefined behavior 因为这些指针指向不相关的对象?或者程序正常/有效(没有 UB)并且因为指针具有不同的值,所以将执行 else 分支?

最佳答案

标准说:

[expr.eq]

The == (equal to) and the != (not equal to) operators group left-to-right. The lvalue-to-rvalue ([conv.lval]), array-to-pointer ([conv.array]), and function-to-pointer ([conv.func]) standard conversions are performed on the operands...

因此,我们正在比较指向相应数组的指针。

If at least one of the operands is a pointer, ... Comparing pointers is defined as follows:

  • If one pointer represents the address of a complete object, and another pointer represents the address one past the last element of a different complete object,72 the result of the comparison is unspecified. [does not apply since neither pointer is past last element]
  • Otherwise, if the pointers are both null, both point to the same function, or both represent the same address, they compare equal. [does not apply since neither is null, neither point to functions, nor represent same address]
  • Otherwise, the pointers compare unequal. [applies]

行为已定义,否则分支将无条件执行。

Unconditionally 无条件 if 语句暗示可能存在错误;很可能作者试图比较数组的内容,而运算符(operator)并没有这样做。


"warning: comparison with string literal results in unspecified behavior"

我认为这个警告消息有点误导。与两个字符串文字的比较将是未指定的:

if ("tri" == "tri")

不确定这个条件是真还是假。

关于c++ - 将字符数组 char u[10] 与字符串文字 "abc"进行比较是否是未定义的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71305813/

相关文章:

powershell - 仅添加真实 MAC 地址

bash - 从多个文件中获取字符串并复制到新文件并将文件名打印到 bash 的第二列

swift - RealityKit——在检测到的平面上可视化网格

python - 独特的骰子组合

r - 一种扩展R向量的有效方法

r - 检查列表中的值是否存在于多列 R data.table 中

android - 如何在撰写的TextField中用逗号格式化数字

flutter - 图标聚集在带有 float 按钮的 flutter 底部导航栏中

r - 如何获取下划线分隔的元素个数

R - 如何将多个 bool 列(不知道有多少)组合成一列