coffeefirst
coffeefirst

Reputation: 135

c++ string compare operator > produces different outputs depending on how two strings are compared

Below code produces different results:

  1. Initialize and assign values to string variables to compare.

string d = "d"; string abc = "abc";

d > abc evaluates to true.

  1. Compare strings. "d" > "abc" evaluates to false.

How do they produce different outputs?

Upvotes: 1

Views: 46

Answers (1)

fuzzything44
fuzzything44

Reputation: 701

"d" is not a std::string. It is a const char *. As such, when you do string d = "d", you set a string to the const char * of {'d', '\0'}. Then when you compare it, the std::string operator> is used instead of the version for a const char *.

Upvotes: 1

Related Questions