Help with CASE Statea

 BBS: Inland Empire Archive
Date: 05-21-92 (09:21)             Number: 152
From: RICHARD VANNOY               Refer#: NONE
  To: ZACK JONES                    Recvd: NO  
Subj: Help with CASE Statea          Conf: (2) Quik_Bas
Let me give you a few examples.

Although I would agree that almost all CASE's can be
rewritten as IF's and almost all IF's can be rewritten as
CASE's, there are several points that you might want to

1.  In a multiple IF, like:

   IF a = 1 THEN ...
   IF a = 2 THEN ...
   IF a = 3 THEN ...   etc.
the compiler *must* check the validity of every statement.
If "a" happens to be 1, the machine does the "1" action(s),
then looks to see if "a = 2" is TRUE, then if "a = 3" is
true, and so on.  This can slow down code considerably!
In a SELECT CASE, if "a" happens to be 1 (best case), the
machine does the "1" stuff and *immediately* drops to the
END CASE statement, *never* even seeing all of the other
possibilities.  When you know that most of the time, "a =
3", then you can put the CASE 3 statement first and speed
up execution of the code.  (Same principle as putting the
most often used subdirectory firstv in the DOS PATH

2.  The CASE statement can be much more readable when there
are multiple possibilities.  Suppose I want to say:

- Upper Case characters, Lower Case characters and minus
  signs are valid input.
- ESCape (don't save), ENTER (save), and F10 (save) will
  say you are finished.
- F1 will pop up a help screen

The following is a lot cleaner, neater and easier to read
than when using the multiple IF statement:

        CASE 45, 48-57, 65-90, 97-122
           'Do valid input stuff
        CASE ESCape%, 13, F10%
           IF NOT ESCape% THEN CALL SaveStuff
           'Do final housekeeping
           'EXIT SUB
        CASE F1%
           CALL PopUpHelp (14)
        CASE ELSE
           'Do nothing, or maybe BEEP.

3.  I have seen this kind of thing posted here several times:
IF a=3 OR (a>4 AND a<10) OR a=99 OR a=200 OR a>300 THEN ...
I would personaly rather see (or try to read) something like:

        3, 5-9, 99, 200, > 300

In closing, let me say that my own personal rule is that if
I have to select from two alternatives, I use IF.  If there
are four or more possibilities, I use CASE.  With three,
it's a toss up and I use either.

> MegaMail 2.1b #0:This is the tagline--><-No, THIS is the tagline!

--- WM v2.01/91-0012
 * Origin: Com-Dat BBS  Hillsboro, OR.  HST (503) 681-0543 (1:105/314)
Outer Court
Echo Basic Postings

Books at Amazon:

Back to BASIC: The History, Corruption, and Future of the Language

Hackers: Heroes of the Computer Revolution (including Tiny BASIC)

Go to: The Story of the Math Majors, Bridge Players, Engineers, Chess Wizards, Scientists and Iconoclasts who were the Hero Programmers of the Software Revolution

The Advent of the Algorithm: The Idea that Rules the World

Moths in the Machine: The Power and Perils of Programming

Mastering Visual Basic .NET