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

标签 c++ pointers language-lawyer

我遇到了 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/

相关文章:

c++ - 如何为 IAsyncOperation 指定回调方法

c++ - 数组元素算作一个共同的初始序列吗?

c++ - 编译器优化 : move variable from stack to register

c++ - 没有临时数组的列表初始化 - 在 GCC 中不起作用

c++ - 没有实现文件时包含头文件?

c++ - C++ 应用程序中的 QML,反之亦然

c - 局部变量的数据突然损坏

c - 通过void修改任何数据指针是否合法**

c - ptr*** 不工作

c++ - 如何将cmake项目移动到子目录?