bool and int

Chris Angelico rosuav at gmail.com
Sat Jan 28 19:32:47 EST 2023


On Sun, 29 Jan 2023 at 11:27, rbowman <bowman at montana.com> wrote:
>
> On Fri, 27 Jan 2023 21:35:11 -0800 (PST), Grant Edwards wrote:
>
> > In Unix shells, a return code of 0 is true and non-0 is false.
>
> That carries over to some C functions like strcmp() although it's more
> complex. strcmp() returns the value of subtracting the nth character of
> string b from string a if the value is not 0. For matching strings, the
> result is 0 for all character positions.
>
> This plays nicely with sorting functions but naive programmers assume it's
> a boolean and strcmp("foo", "foo") should return 1 or true when the
> strings match.
>
> Returning 0 for success gives you much more latitude in return values.

That's not really about booleans, it's more like "imagine subtracting
one string from another". You can compare two integers by subtracting
one from another; you'll get a number that's less than zero, zero, or
greater than zero, just like with strcmp. And yes, that plays
perfectly with sorting functions. So when you want to compare strings,
what do you do? You make something that subtracts one string from
another.

It's "String Compare", not "Are Strings Equal", so it doesn't return a
boolean. Zero for equal makes very good sense, even though a "strings
equal" function would return zero for non-equal.

ChrisA


More information about the Python-list mailing list