Skip to main content
Source Link
user44761
user44761

Before addressing the general case, we can discuss your counter examples.

String comparisons

The same holds for many sorts of comparisons, actually. Such comparisons compute a distance between two objects. When the objects are equal, the distance is minimal. So when the "comparison succeeds", the value is 0. But really, the return value of strcmp is not a boolean, it is a distance, and that what traps unaware programmers doing if (strcmp(...)) do_when_equal() else do_when_not_equal().

In C++ we could redesign strcmp to return a Distance object, that overrides operator bool() to return true when 0 (but you would then be bitten by a different set of problems). Or in plain C just have a streq function that returns 1 when strings are equal, and 0 otherwise.

API calls/program exit code

Here you care about the reason something went wrong, because this will drive the decisions up on error. When things succeed, you don't want to know anything in particular - your intent is realized. The return value must therefore convey this information. It is not a boolean, it is an error code. The special error value 0 means "no error". The rest of the range represent locally meaningful errors you have to deal with (including 1, which often means "unspecified error").

General case

This leaves us with the question: why are boolean values True and False commonly represented with 1 and 0, respectively?

Well, besides the subjective "it feels better this way" argument, here are a few reasons (subjective as well) I can think of:

  • electrical circuit analogy. The current is ON for 1s, and OFF for 0s. I like having (1,Yes,True,On) together, and (0,No,False,Off), rather than another mix

  • memory initializations. When I memset(0) a bunch of variables (be them ints, floats, bools) I want their value to match the most conservative assumptions. E.g. my sum is initally 0, the predicate is False, etc.

Maybe all these reasons are tied to my education - if I had been taught to associate 0 with True from the beginning, I would go for the other way around.

Post Made Community Wiki by user44761