C++:比较运算符>和字符串文字的意外结果

Pri*_*nce 3 c++ pointers

在C++中,std :: string类实现了比较运算符.下面的代码打印AAA

#include <iostream>
using namespace std;
int main() {

    if("9">"111")
        cout << "AAA";
    else 
        cout << "not AAA";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个片段打印not AAA:

#include <iostream>
using namespace std;
int main() {

    if("9">"111")
        cout << "AAA";
    else 
        cout << "not AAA";

    if("99">"990")
        cout << "BBB";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

koc*_*ica 5

您正在比较静态持续时间存储中某处的字符串文字的地址,并且它具有未指定的行为.

std::string像这样使用

#include <iostream>
using namespace std;
int main() {

    if(std::string("9") > std::string("111"))
        cout << "AAA";
    else 
        cout << "not AAA";

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑

有了using namespace std::literals;一个可以用"9" S和"111"秒.

谢谢@sp2danny

  • @ user0042 - 比较*不指向同一数组的元素的两个指针具有未定义的行为. (6认同)
  • 没有_undefined behavior_. (5认同)
  • @StoryTeller实际上,它似乎只是未指明. (5认同)
  • @StoryTeller没有分歧,但答案应该是正确的,未定义和未指定的是相当不同的.菲利普,你会考虑进行修正吗? (2认同)
  • 使用`using namespace std :: literals;`一个可以使用``9"s`和`"111"s` (2认同)