Saturday, December 25, 2004

Old coding thing (from C days)

So if you're not a geek (and for those geeks reading, yes I actually know some non-geeks) I'd recommend skipping this post and going onto my Merry Xmas and some thoughts post.

Was reading a post from The Old New Thing on BOOL vs. VARIANT_BOOL vs. BOOLEAN vs. bool which is an interesting post about the origins of the different boolean standards (and if you've ever had to write code to talk to a dll written in another language you'll understand why I found this interesting). But this reminded me an old C technique which was commonly used to handle menu's (I'm talking text based/command prompt age here, none of this funky mouse stuff)

How C handled booleans
If you've read the link above you'll now know that the original BOOL was defined as an int with two possible values (0 = False, 1 = True).

Now C to see if something was False simply does (x == 0) and True does either (x != 0) or (x > 0) // I can't remember which one it is Which meant that if you wanted to be creative in your functions what you would do is return instead of a boolean you'd return an int, allowing:

if(int x=ShowMenu())
{
princ('You picked menu /n', x);
}
princ('Goodbye');

Ok that's probably not making much sense, but the point is that if you return 0 it meant fail an if check, any other number (or positive number) would be 'true' and so...

Why old menu's used to have 0 as the Exit Menu option
You now should have a good idea where I'm heading here, but to continue... Dos, BBS, Unix (generally text based applications), would usually have a menu that kinda looked like:

1. PINE
2. FTP
3. TELNET
4. MOO
-
0. EXIT

So you'd simply press the appropriate key matching the menu option you wanted (sorry for boring the crap out of coders here, but some people are not used to these old menu's they've only ever used Gui's). Anyways it was a fairly common standard that if the menu used numbers as their accepted characters 0 would be the exit code. Allowing:

while(x)
{
if(x=ShowMenu())
{
switch(x)
1: Pine(); break;
2: Ftp(); break;
3: Telnet(); break;
4: Moo(); break;
}
}


Basically you never had to explicitly code to handle the Exit case, as it was inherently handled by the if() and while().

It's still around!
This particular 'standard' has followed us today by people who call API functions (that return 0 if it fails, and maybe a href if it succeeds) like so:

if setRegValue("HKEY_USER", "Software\Microsoft\Excel", pstrFieldName, pstrValue) then
msgbox "Successfully updated value"
end if

For backwards compatibility you can still compare int's to a Boolean in most languages (even if the language no longer uses int as it's boolean underlying type)

Here endeth the lesson.

No comments: