Boolean Representation

A discussion under ReturnBooleanEvaluations (originally in a Java context) led to a long tangent on representations of conditional/boolean values in various programming languages. What little remains of that discussion has been moved here.

C may return 0 or 1 from conditional expressions, but not all languages do. VisualBasic, for example, returns 0 meaning false, and -1 meaning true. So watch out if you ever have to pass pseudo-booleans between code written in different languages. -- KatyMulvey

ForthLanguage standardized on -1 (all bits set) for true after many years of a defacto standard of 1 for true. There was a lot of discussion of the merits of each representation on news:comp.lang.forth at the time the ANS Forth standard was being finalized.

Advantages of -1 for true:

This is really only an issue for LowLevelLanguages. HighLevelLanguages keep Boolean as a distinct type. -- IanOsgood

It's only an issue for legacy languages. Were a new LowLevelLanguage to arise, I can't see any reason not to keep bool as a separate type, with a well-defined conversion as necessary.

Double complement, flag = !!other_flag; is a C idiom used to convert all non-zero values to 1, C's preferred representation of true. -- thanks to KatyMulvey

Using 1 for true means that true can be stored in a 1-bit BitField and in an unsigned int. It also makes arrays indexed by booleans easy. -- DaveHarris

Similarly, I always figured 1 for true was for C expressions like while (*s) spaces += (*s++ == ' '); Not that I'm recommending this, mind you. -- JimPerry

Rephrased, when "1>0" is defined by the language to return the integer 1, there's no distinguishing that value from other instances of the integer 1. Any coding convention introducing a different boolean type will need to deal with "1>0" and similar compares of primitive types, if only by avoiding them. -- JimPerry

That's not an issue if your language has a boolean type, as in Smalltalk and Java. It does leave the related question of how to encode booleans in non-boolean results. For example, an indexOf() method that needs to return a "not there" indicator as well as the actual index if it is there. Where references are involved, it's natural to use "null" as the "false" indicator. With integers, one tends to return -1 or 0 (depending on where your array subscripts start). I suppose in Smalltalk you have the option of returning either an integer or "false" (or somesuch); do people do that? Java's static type system isn't powerful enough to allow that. I believe DylanLanguage lets you define a type as (the set of integers) | (null), which makes it more explicit. -- DaveHarris

However, mixing error codes with valid return data is a form of InBandSignal that can make functions hard to use.

FalseIsNotAnError


EditText of this page (last edited March 18, 2010) or FindPage with title or text search