Hi all
Before we ruffle our feathers, its ok to use GOTO most of the time but
not all the time.
There are times when GOTO should NEVER be used.
I will explain so bear with me through this.
Use goto when appropriate if you like using them
but NEVER use them to exit a DO loop or FOR loop.
Nor any thing else that resembles a form of a loop
The stack is a list of memory addresses which is constantly
changing. later on here I think you will see what I mean. so keep reading.
The following is not a loop to which I am speaking because
the address where 10 , 15 and 20 reside is not saved in whats called a
stack.
its ok to do this: etc
10
15 do stuff
20 goto 10
But when using a loop dont do this
Do
a = a + 5
if a = 25 then Goto there
loop until x$ = inkey$
there:
And dont do this:
for t = 1 to 30
if t = 12 then goto There
next t
There
:
to exit a loop of any kind then use the EXIT statement. That
will clear the stack.
The reason is that the program uses whats called a stack
which is a list of pointers to where in memory your loop is
running at the moment. in other words when you enter a loop the
beginning and ending address of that loop are recorded in the stack.
that is how the program know what part of the program to loop within.
it says run from such and such address and loop back tosuch and such
address. These are all addresses in memory which can change constantly
depending what your program does.
So if you exit that loop with a GOTO, that information stays in the stack,
if you do that long enough the stack will eventualy fill up and crash your
program or do something unexpectedly
because the GOTO statment does not clear the stack of that info. The stack will eventualy fill up and crash your program if done enough times.
The EXIT statement will clear the stack properly
These are examples of leaving loops properly.
examples:
Do
x = x + 1
if x = 10 then EXIT DO
loop
Another example to use exit
for t = 1 to 30
if t = 12 then exit for
next t
and it is ok to call a sub routine from within a loop because that sub will
return back to the loop where it started, thus not messing up the stack.
It is also ok to use a GOTO within a loop that doesnt leave the loop,,, This is a very dumb example but gets the point across I think.
DO
Again:
a = a + 1
if a < 5 then goto again
print "We counted to 5 but nobody seen it";
EXIT DO
LOOP
sleep
system
I hope Ive explained this fairly well. Im not against using goto sometimes but
there are situations where it is not good practice.
Dustie