1

I am studying C++. I am surprised that it can compare strings. The following code compiles and runs successfully for strings a and b.

if (b >= a)
{}

What does it mean?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Adola
  • 337
  • 1
  • 16
  • The posted code does not compile: `temp.cpp:1:1: error: expected unqualified-id` – Jeremy Friesner Sep 04 '20 at 06:13
  • Your surprise is surprising, presumably you've heard of alphabetic order, or dictionary order? – john Sep 04 '20 at 06:17
  • @john I tested using b="Bb" and a="Aa" and many others before asking the question, and got that it's true that b>a. I thought of that but I am not certain. I wanted to know how exactly they order string rather than just knowing by doing trial and error. – Adola Sep 04 '20 at 06:27
  • One more thing - often forgotten - the result of the compare is implementation defined. For example, a system with ASCII encoding will put upper case letters first, EBCDIC puts lower case letters first. Despite functions like `tolower` and `toupper` existing, there's still no case-instentive-compare function built into standard C++. (But we get absolutely vital things in C++20 like a new formatting library ;-) ) – Bathsheba Sep 04 '20 at 06:45
  • @Adola Sorry I thought you were surprised that there is any comparison possible at all. As Bathsheba says there is no standard order. It would be a crazy system where "a" > "b" but such a system is allowed. The commonest order is that defined by the [ASCII encoding](https://en.wikipedia.org/wiki/ASCII). – john Sep 04 '20 at 07:04

1 Answers1

2

All comparisons of std::string are lexicographical. See std::basic_string::operator>=.

You can find an excellent answer which explains this in detail here: Using the less than comparison operator for strings. The operators < and >= are not equivalent, but the principle is the same.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
  • Probably a good idea to add the general link as well [std::basic_string](https://en.cppreference.com/w/cpp/string/basic_string) – David C. Rankin Sep 04 '20 at 06:16