Mail Archives: djgpp/1999/07/31/05:34:55
Groovy hepcat Tom was jivin' on Thu, 22 Jul 1999 14:24:32 -0400 in
comp.os.msdos.programmer.
Iteration vs. Recursion...'s a cool scene! Dig it!
>I have a keyboard input program that runs one thing if one key is entered
>and another if another key is entered. There are about ten different
>options. That means I have ten different if statements. I am using
>recursion because after I get one input I do the program over again.
>
>The only problem with this program is that I have to hold down the key for
>about a second before anything is recognized. Is there any way to speed
>this up? Possibly by using iteration instead of recursion. Here is the
>code. Any suggestions are greatly appreciated. I left out the program
>names and variables not needed. I use getch to catch the keystrokes. I
>tried using the bioskey but that didn't speed anything up. I am using DJGPP
>to compile this:
By now you know that switch can be of use to you, and you need only
call getch() once. But, iteration will be much better, even though you
*probably* could get away with recursion. The iterative approach is
almost always more efficient. You might not notice any speed
difference (OTOH you might), since computers can do things too fast to
for the eye to see. However, if you let the program run for some time
you may see the program crash as it runs out of stack space. Recursion
is really only good for tasks that can't easily be done iteratively.
And this particular task certainly doesn't lend itself to recursion.
So, IMHO you should take the (more logical) iterative approach, even
if recursion works:
int c;
while((c = getch()) != EOF && c != your_quit_key)
switch(c)
{
case x:
/* do stuff */
break;
case y:
/* do other stuff */
break;
...
case f: case g: /* c == f || c == g */
/* whatever */
break;
...
}
--
----- Dig the EVEN NEWER, MORE IMPROVED news sig!! -----
-------------- Shaggy was here! ---------------
http://aardvark.apana.org.au/~phaywood/
============= Ain't I'm a dawg!! ==============
- Raw text -