Friday, July 17, 2015

(x, why?) Mini: Boolean

(Click on the comic if you can't see the full image.)
(C)Copyright 2015, C. Burke.

If (isfunny) then leave-praise-share else nevermind

Boolean is a logical value equal to True or False and is used in logic (such as in computer programming).

The interesting thing about them was when I found out that False has a zero value, but True isn't equal to 1. In fact, True is simply "not zero", literally any value other than zero (or possibly "null", which is something else and I'm not going there right now).

That means that in situations where you might write "If x != 0 then" (Note: != mean "not equal to" in many computer languages"), you could just write "If x then" because any value other than 0 (which we didn't want) would evaluate as True! This was great! ... except that my professors condemned this as "clever coding" which was harder to read, decipher and maintain, so Don't Do It.

I'm not a programmer by trade any more, but from what I read, clever coding could be the standard, for all I know, because it executes faster, and it's more of a feature of languages like C than it was of PL/I or Pascal.

Final note: "Boolean" is named after George Boole, so it gets a capital "B", like "Venn diagram".

Oh, and this is a bullion cube joke, if you didn't get that. You don't use "Boolean cubes", except maybe in roleplaying games.

Come back often for more funny math and geeky comics.

1 comment:

Anonymous said...

First off, I'm not really a programmer either but I keep doing it here and there and here are my thoughts about what you call clever programming:

- In a strictly typed language where your x is Boolean and can hence only be true or false, it is accepted and in fact very common to write "if x then" instead of "if x == true then".

- Yet this is done for brevity/legibility, in any compiled language there is zero difference in speed (the compiler takes care of optimizing needless things away anyways).

- The trouble starts in a loosely typed language where x is not declared and hence has no fixed type, so it could be assigned to a Boolean, an integer, a string, or even an object. Here, if you write "if x then" it might not always do what you thought. The if will try to cast x into a Boolean applying a rule similar to the one you mentioned (0 means false, \neq 0 means true). A typical example where this goes wrong is when x is the result of a function call. A function might for instance return an integer if things go well but in the rare case something goes wrong it returns a Boolean "false". Now you actually need to check whether x is false or whether it is zero because zero might mean success. Loosely typed languages usually allow this. For example, in PHP you can read things like "if x===false" where the three equal signs mean "identical" (that is same value and same type). Just in case you ever wonder, there may be good reason to do so. ;-)