Flow-control structures: Difference between revisions

no edit summary
(add C)
No edit summary
Line 196:
# some code
goto FORK;
==[[Pop11]]==
[[Category:Pop11]]
 
===quitloop===
quitloop with argument exits from nested loops:
 
<pre>
while condition1 do
while condition2 do
if condition3 then
quitloop(2);
endif;
endwhile;
endwhile;
</pre>
 
above quitloop(2) exits from both loops.
 
===goto===
 
goto l transfers control to the label l. goto may be used to exits from
nested loops:
 
<pre>
while condition1 do
while condition2 do
if condition3 then
goto l;
endif;
endwhile;
endwhile;
l:;
</pre>
 
Another use is to implement finite state machines:
 
<pre>
state1:
DO_SOMETHING();
if condition1 then
goto state1;
elseif condition2 then
goto state2;
....
else
goto stateN;
endif;
state2:
....
...
...
stateN:
....
</pre>
 
Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure
calls:
 
<pre>
define outer();
define inner(n);
if n = 0 then
goto final;
endif;
inner(n - 1);
enddefine;
inner(5);
final:;
enddefine;
</pre>
 
This is useful to exit early from succesful recursive search, and for
exception handling.
 
===go_on===
 
go_on is a multiway jump
 
<pre>
go_on expression to lab1, lab2, ..., labN else elselab ;
</pre>
 
If expression has value K the above will jump to label labK, if
expression is not an ingeger, or if it ouside range from 1 to N,
then control passes to label elselab. The else part may be
omitted (then out of range values of expression cause an exception).
 
There is a more structured variant of go_on:
 
go_on expression to lab :
lab 1 : statement1;
lab 2 : statement2;
....
endgo_on;
 
where lab is a prefix choosen by the user.
 
===return===
 
return ends execution of current function. In simplest form
it is just:
 
<pre>
return;
</pre>
 
but it is also possible to specify one or more return values:
 
<pre>
return(val1, val2, val3);
</pre>
 
===chain===
 
chain has effect of "tail call" but is not nececcarly in tail position
More precisely inside proc1
 
<pre>
chain proc2(x1, x2, x3);
</pre>
 
finishes execution of proc1 and transfers control to
the proc2 passing it x1, x2, and x3 as arguments.
On return from proc2 control passes to caller of proc1.
 
Remark: Pop11 does not perform "tail call optimization", one has to
explicitely use chain.
 
==[[Tcl]]==
Line 211 ⟶ 338:
Eg. defining a command to perform some operation for each line of an input file:
proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
while {[gets $filechan line] != -1} {
uplevel 1 $code ; # Run supplied code in caller's scope
}
close $filechan
Anonymous user