Can someone explain what is happening when using < or > on strings in C++?

  • A+
Category:Languages

While working through a C++ book I came across an example that was comparing two strings using >. I played around with the code and found that these two statements do not evaluate to the same thing. Could someone explain what is happening when using < or > on strings in C++?

string s = "fool";  cout << ("fool" < "ape"); // returns true (1) cout << (s < "ape"); //returns false (0) 

 


"fool" and "ape" are string literals and their type is a built-in type (array of const char, actually), so you get the built-in definition of operator<. Specifically, you get array-to-pointer decay, followed by pointer comparison.

Pointer comparison between items in different arrays is forbidden, so the comparison has an unspecified result (it may even not be repeatable).

The other comparison, s < "ape", is very different. One of the operands has class type, so an overloaded operator provided by std::string is used. That overload actually knows about string comparison.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: