Reputation: 954
I wanted to see if the Less Than operator (<
) would work on strings. Well, it did. I started to experiment with it, and it turns out, I got the same result, regardless of the situtaion. The string on the left is always less than the string on the right, even if I swap the strings. Curious on why it did this, I tried to look up what the <
operator actually does for strings. I read that it does a lexicographical comparison of the two strings. Still, this did not answer why my code was doing what it was doing. For example:
int main () {
if ("A" < "B")
std::cout << "Yes";
else
std::cout << "No";
return 0;
}
It would output Yes
. That makes sense. But when I swap the strings:
int main () {
if ("B" < "A")
std::cout << "Yes";
else
std::cout << "No";
return 0;
}
It would still output Yes
. I don't know if I am just being ignorant right now and not fully understanding what is happening here, or if there is something wrong.
Upvotes: 3
Views: 216
Reputation: 4750
You are comparing the pointer to the string "A" with the pointer to the string "B".
If you want to compare just the value in the chars then use the single quote 'A' and 'B', if you want to compare strings then use the std::string class std::string("A") < std::string("B")
or strcmp()
Upvotes: 3
Reputation: 409136
It's because a string literal gives you a pointer to a read-only array containing the string (plus its terminator). What you are comparing are not the strings but the pointers to these strings.
Use std::strcmp
if you want to compare C-style strings. Or use std::string
which have overloaded comparison operators defined.
Upvotes: 7