When we use strcmp(str1, str2); or str1.compare(str2); the return values are like -1, 0 and 1, for str1 < str2, str1 == str2 or str1 > str2 respectively.
The question is, is it defined like this for a specific reason?
For instance, in binary tree sorting algorithm, we push smaller values to the left child and larger values to the right child. This strcmp or string::compare functions seem to be perfect for that. However, does anyone use string matching in order to sort a tree (integer index are easier to use) ?
So, what is the actual purpose of the three return values ( -1, 0, 1). Why cant it just return 1 for true, and 0 for false?
Thanks
The purpose of having three return values is exactly what it seems like: to answer all questions about string comparisons at once.
Everyone has different needs. Some people sometimes need a simple less-than test;
strncmpprovides this. Some people need equality testing;strncmpprovides this. Some people really do need to know the full relationship between two strings;strncmpprovides this.What you absolutely don’t want is someone writing this:
That’s doing two potentially expensive comparison operations.
strlessalso knows if they were equal, because it had to get to the end of both strings to return that it was not less.Oh, and FYI: the return values isn’t -1 or +1; it’s greater than zero or less than zero. Or zero if they’re equal.