Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less Than operator on string comparison yields same result no matter the situation

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.

like image 219
Greg M Avatar asked Dec 08 '25 18:12

Greg M


2 Answers

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.

like image 92
Some programmer dude Avatar answered Dec 11 '25 06:12

Some programmer dude


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()

like image 20
Paolo Brandoli Avatar answered Dec 11 '25 07:12

Paolo Brandoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!