0

When normally comparing the string this way:

#include <iostream>

using namespace std;

int main()
{
    string a = "yb";
    string b = "ya";
    cout<<(a>b);

    return 0;
}

result comes out 1. Which is right.

But when performing the same operation in this way:

#include <iostream>
using namespace std;
int main()
{
    cout<<("yb">"ya");

    return 0;
}

result is coming out 0.

How is this possible?

  • 3
    In the second case, you aren't comparing `std::string` objects but `const char*` pointers. – Adrian Mole Jun 04 '22 at 12:47
  • 2
    `("yb">"ya");` just compares two `const char*` pointers, not `std::string` instances. You may change that to `cout<<("yb"s>"ya"s);` to get it working as intended. – πάντα ῥεῖ Jun 04 '22 at 12:48
  • Does this answer your question? [C++ Comparison of String Literals](https://stackoverflow.com/questions/27450021/c-comparison-of-string-literals) – ChrisMM Jun 04 '22 at 13:14

1 Answers1

2

"yb" and "ya" have type char const[3]; they are arrays located somewhere in the memory containing the chars in the string literal and the terminating 0 char.

When doing ("yb">"ya") those objects decay to char const* and you're comparing pointers. Where the data is stored is compiler implementation defined and you cannot rely on the result.

To compare std::strings, you'd need to write

std::cout<<(std::string("yb")>std::string("ya"));

instead.

fabian
  • 80,457
  • 12
  • 86
  • 114