Flow-control structures: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Z80 Assembly}}: added JR and interrupts.)
m (→‎{{header|Ada}}: added 'return')
 
(28 intermediate revisions by 11 users not shown)
Line 1: Line 1:
{{Task|Control Structures}}
{{Task|Control Structures}}
{{Control Structures}}
{{Control Structures}}
[[Category:Flow control]]


;Task:
;Task:
Line 20: Line 21:
===Loops===
===Loops===
11l supports ''L.break'' and ''L.continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
11l supports ''L.break'' and ''L.continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
<lang 11l>V n = 10
<syntaxhighlight lang="11l">V n = 10
Int result
Int result


Line 31: Line 32:
L.was_no_break
L.was_no_break
result = -1
result = -1
print(‘No odd factors found’)</lang>
print(‘No odd factors found’)</syntaxhighlight>
In addition, as shown in the foregoing example, 11l loops support an ''L.was_no_break'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target.
In addition, as shown in the foregoing example, 11l loops support an ''L.was_no_break'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target.


Line 38: Line 39:
===Unconditional Branch (B)===
===Unconditional Branch (B)===
To perform a 'goto'.
To perform a 'goto'.
<lang 360asm>
<syntaxhighlight lang="360asm">
B TESTPX goto label TESTPX
B TESTPX goto label TESTPX
BR 14 goto to the address found in register 14
BR 14 goto to the address found in register 14
</syntaxhighlight>
</lang>
===Branch and Link (BAL)===
===Branch and Link (BAL)===
To perform a 'call' to a subroutine. The first register at execution time is the next sequential address to allow a 'return'.
To perform a 'call' to a subroutine. The first register at execution time is the next sequential address to allow a 'return'.
<lang 360asm>
<syntaxhighlight lang="360asm">
LA 15,SINUSX load in reg15 address of function SINUSX
LA 15,SINUSX load in reg15 address of function SINUSX
BALR 14,15 call the subroutine SINUX and place address RETPNT in reg14
BALR 14,15 call the subroutine SINUX and place address RETPNT in reg14
Line 52: Line 53:
...
...
BR 14 return to caller
BR 14 return to caller
</syntaxhighlight>
</lang>


===Conditional Branch (BC)===
===Conditional Branch (BC)===
Fistly a compare instruction set the condition code (cc), secondly a conditional branch is performed.
Fistly a compare instruction set the condition code (cc), secondly a conditional branch is performed.
<lang 360asm>
<syntaxhighlight lang="360asm">
L 4,A Load A in register 4
L 4,A Load A in register 4
C 4,B Compare A with B
C 4,B Compare A with B
Line 65: Line 66:
BNL TESTGE Branch on Not Low if A>=B then goto TESTGE
BNL TESTGE Branch on Not Low if A>=B then goto TESTGE
BNE TESTNE Branch on Not Equal if A<>B then goto TESTNE
BNE TESTNE Branch on Not Equal if A<>B then goto TESTNE
</syntaxhighlight>
</lang>
===Branch on Count (BCT)===
===Branch on Count (BCT)===
To perform unconditional loops.
To perform unconditional loops.
<lang 360asm>
<syntaxhighlight lang="360asm">
LA 3,8 r3 loop counter
LA 3,8 r3 loop counter
LOOP EQU *
LOOP EQU *
... loop 8 times (r3=8,7,...,2,1)
... loop 8 times (r3=8,7,...,2,1)
BCT 3,LOOP r3=r3-1 ; if r3<>0 then loop
BCT 3,LOOP r3=r3-1 ; if r3<>0 then loop
</syntaxhighlight>
</lang>
===Branch on Index (BX.)===
===Branch on Index (BX.)===
BXLE to perform loops in old Fortran style with 3 registers.
BXLE to perform loops in old Fortran style with 3 registers.
<lang 360asm>
<syntaxhighlight lang="360asm">
* do i=1 to 8 by 2
* do i=1 to 8 by 2
L 3,1 r3 index and start value 1
L 3,1 r3 index and start value 1
Line 84: Line 85:
... loop 4 times (r3=1,3,5,7)
... loop 4 times (r3=1,3,5,7)
BXLE 3,4,LOOPI r3=r3+r4; if r3<=r5 then loop
BXLE 3,4,LOOPI r3=r3+r4; if r3<=r5 then loop
</syntaxhighlight>
</lang>
BXH to perform backward loops with 3 registers.
BXH to perform backward loops with 3 registers.
<lang 360asm>
<syntaxhighlight lang="360asm">
* do i=8 to 1 by -2
* do i=8 to 1 by -2
L 3,1 r3 index and start value 8
L 3,1 r3 index and start value 8
Line 94: Line 95:
... loop 4 times (r3=8,6,4,2)
... loop 4 times (r3=8,6,4,2)
BXH 3,4,LOOPI r3=r3+r4; if r3>r5 then loop
BXH 3,4,LOOPI r3=r3+r4; if r3>r5 then loop
</syntaxhighlight>
</lang>


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
Line 100: Line 101:
===JMP===
===JMP===
The jump instruction immediately jumps to any address:
The jump instruction immediately jumps to any address:
<lang 6502asm> JMP $8000 ;immediately JuMP to $8000 and begin executing
<syntaxhighlight lang="6502asm"> JMP $8000 ;immediately JuMP to $8000 and begin executing
;instructions there.</lang>
;instructions there.</syntaxhighlight>
The indirect jump instruction immediately jumps to the address contained in the address:
The indirect jump instruction immediately jumps to the address contained in the address:
<lang 6502asm> JMP ($8000) ;immediately JuMP to the address in memory locations
<syntaxhighlight lang="6502asm"> JMP ($8000) ;immediately JuMP to the address in memory locations
;$8000 and $8001</lang>
;$8000 and $8001</syntaxhighlight>


===JSR===
===JSR===
The jump to subroutine instruction pushes the address of the next instruction minus one onto the stack and jumps to any address:
The jump to subroutine instruction pushes the address of the next instruction minus one onto the stack and jumps to any address:
<lang 6502asm> JSR $8000 ;Jump to SubRoutine</lang>
<syntaxhighlight lang="6502asm"> JSR $8000 ;Jump to SubRoutine</syntaxhighlight>
A return from subroutine instruction pops the return address off the stack, adds one, and jumps to that location:
A return from subroutine instruction pops the return address off the stack, adds one, and jumps to that location:
<lang 6502asm> RTS ;ReTurn from Subroutine</lang>
<syntaxhighlight lang="6502asm"> RTS ;ReTurn from Subroutine</syntaxhighlight>

===NMI===
This isn't a CPU instruction, it stands for Non-Maskable Interrupt. A non-maskable interrupt will push the program counter and the flags (in that order) then execute <code>JMP ($FFFA)</code>, thereby reading the address stored there and jumping to that address. This interrupt cannot be disabled with <code>SEI</code>. The code at that address will need to end in <code>RTI</code> to properly return from the interrupt.


===BRK===
===BRK===
Similar to NMI, except the CPU executes execute <code>JMP ($FFFE)</code> instead. This is intended for debugging but is not of much practical use. Returning from this interrupt will skip the instruction after the <code>BRK</code>.
A break instruction causes a non-maskable interrupt (setting the interrupt flag), pushes the current program counter address plus one onto the stack, pushes the flags onto the stack, then jumps to the address in the break vector (commonly at $FFFE and $FFFF):

<lang 6502asm> BRK ;BReaK</lang>
===IRQ===
The return from interrupt instruction pops the flags off the stack, pops the return address off the stack, adds one, and jumps to that location:
This is a generic interrupt that jumps to the handler stored in memory location <code>$FFFE</code>, but unlike <code>BRK</code> it doesn't skip anything when it returns. This can be disabled with <code>SEI</code>, and often can be configured at runtime to occur upon specific events, unlike NMI which usually is triggered by the same event. Use <code>RTI</code> to return from this interrupt.
<lang 6502asm> RTI ;ReTurn from Interrupt</lang>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
<code>JMP</code>,<code>JSR</code>,<code>RTS</code>, and branching work almost identical to [[6502 Assembly]]. There are a few exceptions:
<code>JMP</code>,<code>JSR</code>,<code>RTS</code>, and branching work almost identical to [[6502 Assembly]]. There are a few exceptions:
* <code>BCS</code> and <code>BCC</code> are the opposite for the purposes of unsigned comparisons.
* Compared to the 6502, <code>BCS</code> and <code>BCC</code> are the opposite for the purposes of unsigned comparisons. (The 6502 is actually the odd one out here - on most architectures "carry clear" represents greater than or equal, but 6502 is the opposite!)
* An additional <code>BSR</code> can be used for nearby subroutines. This is quicker than a <code>JSR</code> but has a limited range. It is also <i>not</i> relocatable, in the sense that if you copy a routine to RAM that uses this instruction and try to execute it there, unless you also copied the routine that you're <code>BSR</code>ing to, you're in for a nasty surprise. Many assemblers will auto-convert JSR to BSR and there's no easy way to conditionally stop that from happening except by inlining bytecode.
* An additional <code>BSR</code> can be used for nearby subroutines. This is "cheaper" than a <code>JSR</code>.
* <code>DBRA</code> is used for looping. A register operand is decremented with each loop. The loop terminates when the value in the register underflows from 0 to FFFF.
* <code>DBRA</code> is used for looping. A register operand is decremented with each loop. The loop terminates when the value in the register underflows from <tt>0</tt> to <tt>0xFFFF</tt>. As a result, the number of times you want to loop must be reduced by one. <code>DBRA</code> stands for "decrement, branch always" and there are other condition codes you can use, that will decrement the register operand (at word length) and branch <i>unless</i> the condition is met.
* <code>TRAP #</code> is often used by the firmware to perform built-in tasks such as reading a keyboard or mouse input. Some systems (such as the Sega Genesis and NEO GEO) allow the programmer to alter the destination of the traps, allowing for custom error handlers. (However, these locations are usually in ROM and thus cannot be changed at runtime.)


=={{header|Ada}}==
=={{header|Ada}}==


===goto===
===goto===
<lang ada><<Top>>
<syntaxhighlight lang="ada"><<Top>>
Put_Line("Hello, World");
Put_Line("Hello, World");
goto Top;</lang>
goto Top;</syntaxhighlight>


===exit===
===exit===
Exit is used to break out of loops. Exit can be used with a label to break out of an inner loop to an outer loop and its enclosing outer loop
Exit is used to break out of loops. Exit can be used with a label to break out of an inner loop to an outer loop and its enclosing outer loop:
<lang ada>Outer:
<syntaxhighlight lang="ada">Outer:
loop
-- do something
loop
loop
-- do something
if Finished then
loop
-- do something else
exit Outer; -- exits both the inner and outer loops
exit Outer; -- exits both the inner and outer loops
end loop;
end if;
-- do something else
end loop;</lang>
end loop;
end loop Outer;</syntaxhighlight>
or, more idiomatically,
<syntaxhighlight lang="ada">Outer:
loop
-- do something
loop
exit Outer when Finished;
-- do something else
end loop;
end loop Outer;</syntaxhighlight>

===return===
A procedure can be exited early, if there’s no more to be done.
<syntaxhighlight lang="ada">procedure Foo is
begin
-- do something
if Nothing_More_To_Do then
return;
end if;
-- do more
end Foo;</syntaxhighlight>

===asynchronous transfer of control===
===asynchronous transfer of control===
A sequence of operation can be aborted with an asynchronous transfer of control to an alternative:
A sequence of operation can be aborted with an asynchronous transfer of control to an alternative:
<lang ada>select
<syntaxhighlight lang="ada">select
delay 10.0;
delay 10.0;
Put_Line ("Cannot finish this in 10s");
Put_Line ("Cannot finish this in 10s");
Line 149: Line 177:
-- do some lengthy calculation
-- do some lengthy calculation
...
...
end select;</lang>
end select;</syntaxhighlight>
The alternative can be a delay statement or else an entry point call followed by a sequence of operations. The statement blocks at the delay or entry call and executes the sequence of the operation introduced by '''then abort'''. If blocking is lifted before completion of the sequence, the sequence is aborted and the control is transferred there.
The alternative can be a delay statement or else an entry point call followed by a sequence of operations. The statement blocks at the delay or entry call and executes the sequence of the operation introduced by '''then abort'''. If blocking is lifted before completion of the sequence, the sequence is aborted and the control is transferred there.


Line 160: Line 188:
See also [[Exceptions#ALGOL_68|Exceptions]] to see how '''ALGOL 68''' handles ''transput'' events.
See also [[Exceptions#ALGOL_68|Exceptions]] to see how '''ALGOL 68''' handles ''transput'' events.
===One common use of a label in '''ALGOL 68''' is to break out of nested loops.===
===One common use of a label in '''ALGOL 68''' is to break out of nested loops.===
<lang algol68>(
<syntaxhighlight lang="algol68">(
FOR j TO 1000 DO
FOR j TO 1000 DO
FOR i TO j-1 DO
FOR i TO j-1 DO
Line 171: Line 199:
OD;
OD;
done: EMPTY
done: EMPTY
);</lang>
);</syntaxhighlight>
===Multi way jump using labels and '''EXIT''' to return result ===
===Multi way jump using labels and '''EXIT''' to return result ===
<lang algol68>STRING medal = (
<syntaxhighlight lang="algol68">STRING medal = (
[]PROC VOID award = (gold,silver,bronze);
[]PROC VOID award = (gold,silver,bronze);


Line 184: Line 212:
);
);


print(("Medal awarded: ",medal, new line));</lang>
print(("Medal awarded: ",medal, new line));</syntaxhighlight>
===Another use is to implement finite state machines ===
===Another use is to implement finite state machines ===
<lang algol68>STRING final state = (
<syntaxhighlight lang="algol68">STRING final state = (
INT condition;
INT condition;
PROC do something = VOID: condition := 1 + ENTIER (3 * random);
PROC do something = VOID: condition := 1 + ENTIER (3 * random);
Line 206: Line 234:
"State N"
"State N"
);
);
print(("Final state: ",final state, new line));</lang>
print(("Final state: ",final state, new line));</syntaxhighlight>
===ALGOL 68G implements a Refinement Preprocessor to aid with top down code development ===
===ALGOL 68G implements a Refinement Preprocessor to aid with top down code development ===
<lang algol68># example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
<syntaxhighlight lang="algol68"># example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
determine first generation;
determine first generation;
WHILE can represent next generation
WHILE can represent next generation
Line 229: Line 257:
printf (($lz","3z","3z","2z-d$, current,
printf (($lz","3z","3z","2z-d$, current,
$xz","3z","3z","2z-d$, previous,
$xz","3z","3z","2z-d$, previous,
$xd.n(real width - 1)d$, current / previous)).</lang>
$xd.n(real width - 1)d$, current / previous)).</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 244: Line 272:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
As well as structured flow-control structures (loops, if-then-else, etc.) Algol W has a goto statement. A goto can lead out of the current procedure, which can be used for error handling. Goto can be written as "goto" or "go to".
As well as structured flow-control structures (loops, if-then-else, etc.) Algol W has a goto statement. A goto can lead out of the current procedure, which can be used for error handling. Goto can be written as "goto" or "go to".
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
integer i;
integer i;
integer procedure getNumber ;
integer procedure getNumber ;
Line 261: Line 289:
writeon( "negative" );
writeon( "negative" );
endProgram:
endProgram:
end.</lang>
end.</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
<lang ARM Assembly>SWI n ;software system call
<syntaxhighlight lang="arm assembly">SWI n ;software system call
B label ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
B label ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
;In fact, almost any instruction can be made conditional to avoid branching.
;In fact, almost any instruction can be made conditional to avoid branching.
Line 272: Line 300:


BX Rn ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
BX Rn ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
;BX LR is commonly used to return from a subroutine.</lang>
;BX LR is commonly used to return from a subroutine.

addeq R0,R0,#1 ;almost any instruction can be made conditional. If the flag state doesn't match the condition code, the instruction
;has no effect on registers or memory.</syntaxhighlight>

=={{header|Arturo}}==
=== return ===
return from the function currently being execute
=== loop control ===
Arturo's loop control statements are: <code>break</code> and <code>continue</code>
=== exceptions ===
Normally, in Arturo we'd use either <code>try [...]</code> or <code>try? [...] else [...]</code> blocks.


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox, calling Label1
<syntaxhighlight lang="autohotkey">MsgBox, calling Label1
Gosub, Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
MsgBox, Label1 subroutine finished
Line 288: Line 327:
Label2:
Label2:
MsgBox, Label2 will not return to calling routine
MsgBox, Label2 will not return to calling routine
Return</lang>
Return</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 294: Line 333:
The [awk] programming language is data driven. However, Awk has ''break'' and ''continue'' for loop control, as in C.
The [awk] programming language is data driven. However, Awk has ''break'' and ''continue'' for loop control, as in C.


<lang awk>$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
<syntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
2
4
4
6
6
8</lang>
8</syntaxhighlight>




=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
gosub subrutina
gosub subrutina


Line 315: Line 354:
return
return
end
end
</syntaxhighlight>
</lang>




Line 321: Line 360:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
BBC BASIC has '''GOSUB''' and '''GOTO''' but they are deprecated.
BBC BASIC has '''GOSUB''' and '''GOTO''' but they are deprecated.
<lang bbcbasic> GOSUB subroutine
<syntaxhighlight lang="bbcbasic"> GOSUB subroutine
(loop)
(loop)
Line 331: Line 370:
PRINT "In subroutine"
PRINT "In subroutine"
WAIT 100
WAIT 100
RETURN</lang>
RETURN</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
In Bracmat, the thing that comes closest to a GOTO construct is evaluation of a variable that contains some code, ending with an evaluation of the same variable. Due to tail recursion optimization this can run forever. Example:
In Bracmat, the thing that comes closest to a GOTO construct is evaluation of a variable that contains some code, ending with an evaluation of the same variable. Due to tail recursion optimization this can run forever. Example:
<lang bracmat> ( LOOP
<syntaxhighlight lang="bracmat"> ( LOOP
= out$"Hi again!"
= out$"Hi again!"
& !LOOP
& !LOOP
)
)
& out$Hi!
& out$Hi!
& !LOOP</lang>
& !LOOP</syntaxhighlight>
{{out}}
{{out}}
<pre>Hi!
<pre>Hi!
Line 352: Line 391:
===goto===
===goto===
One common use of goto in C is to break out of nested loops.
One common use of goto in C is to break out of nested loops.
<lang c>int main()
<syntaxhighlight lang="c">int main()
{
{
int i,j;
int i,j;
Line 364: Line 403:
out:
out:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp|C#}}==
===return===
===return===
terminates the function and returns control to the caller.
terminates the function and returns control to the caller.
<lang csharp>int GetNumber() {
<syntaxhighlight lang="csharp">int GetNumber() {
return 5;
return 5;
}</lang>
}</syntaxhighlight>
===throw===
===throw===
throws (or rethrows) an exception. Control is transferred to the nearest catch block capable of catching the exception.<br/>
throws (or rethrows) an exception. Control is transferred to the nearest catch block capable of catching the exception.<br/>
A <code>finally</code> block is always executed before control leaves the <code>try</code> block.
A <code>finally</code> block is always executed before control leaves the <code>try</code> block.
<lang csharp>try {
<syntaxhighlight lang="csharp">try {
if (someCondition) {
if (someCondition) {
throw new Exception();
throw new Exception();
Line 384: Line 423:
} finally {
} finally {
cleanUp();
cleanUp();
}</lang>
}</syntaxhighlight>
===yield return and yield break===
===yield return and yield break===
In a generator method, <code>yield return</code> causes the method to return elements one at a time. To make this work, the compiler creates a state machine behind the scenes. <code>yield break</code> terminates the iteration.
In a generator method, <code>yield return</code> causes the method to return elements one at a time. To make this work, the compiler creates a state machine behind the scenes. <code>yield break</code> terminates the iteration.
<lang csharp>public static void Main() {
<syntaxhighlight lang="csharp">public static void Main() {
foreach (int n in Numbers(i => i >= 2) {
foreach (int n in Numbers(i => i >= 2) {
Console.WriteLine("Got " + n);
Console.WriteLine("Got " + n);
Line 400: Line 439:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 409: Line 448:
===await===
===await===
is used to wait for an asynchronous operation (usually a Task) to complete. If the operation is already completed when <code>await</code> is encountered, the method will simply continue to execute. If the operation is not completed yet, the method will be suspended. A continuation will be set up to execute the rest of the method at a later time. Then, control will be returned to the caller.
is used to wait for an asynchronous operation (usually a Task) to complete. If the operation is already completed when <code>await</code> is encountered, the method will simply continue to execute. If the operation is not completed yet, the method will be suspended. A continuation will be set up to execute the rest of the method at a later time. Then, control will be returned to the caller.
<lang csharp>async Task DoStuffAsync() {
<syntaxhighlight lang="csharp">async Task DoStuffAsync() {
DoSomething();
DoSomething();
await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
DoSomethingElse();
DoSomethingElse();
}
}
</syntaxhighlight>
</lang>
===break and continue===
===break and continue===
<code>continue</code> causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.<br/>
<code>continue</code> causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.<br/>
Line 421: Line 460:
<code>goto Label;</code> will cause control to jump to the statement with the corresponding label. This can be a <code>case</code> label inside a <code>switch</code>.<br/>
<code>goto Label;</code> will cause control to jump to the statement with the corresponding label. This can be a <code>case</code> label inside a <code>switch</code>.<br/>
Because the label must be in scope, <code>goto</code> cannot jump inside of a loop.
Because the label must be in scope, <code>goto</code> cannot jump inside of a loop.
<lang csharp>while (conditionA) {
<syntaxhighlight lang="csharp">while (conditionA) {
for (int i = 0; i < 10; i++) {
for (int i = 0; i < 10; i++) {
if (conditionB) goto NextSection;
if (conditionB) goto NextSection;
Line 427: Line 466:
}
}
}
}
NextSection: DoOtherStuff();</lang>
NextSection: DoOtherStuff();</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
=== goto ===
=== goto ===
{{works with|GCC|3.3.4}}
{{works with|GCC|3.3.4}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


int main()
int main()
Line 439: Line 478:
std::cout << "Hello, World!\n";
std::cout << "Hello, World!\n";
goto LOOP;
goto LOOP;
}</lang>
}</syntaxhighlight>


Note that "goto" may also be used in conjunction with other forms of branching.
Note that "goto" may also be used in conjunction with other forms of branching.
Line 447: Line 486:


Exceptions are a way to give control back to a direct or indirect caller in case of an error. Note that throwing exceptions is usually very expensive, therefore they generally should only be used for exceptional situations.
Exceptions are a way to give control back to a direct or indirect caller in case of an error. Note that throwing exceptions is usually very expensive, therefore they generally should only be used for exceptional situations.
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <ostream>
#include <ostream>


Line 517: Line 556:
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
}
}
}</lang>
}</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 539: Line 578:
=== GO TO ===
=== GO TO ===
Basic use:
Basic use:
<lang cobol> PROGRAM-ID. Go-To-Example.
<syntaxhighlight lang="cobol"> PROGRAM-ID. Go-To-Example.


PROCEDURE DIVISION.
PROCEDURE DIVISION.
Line 546: Line 585:


GO TO Foo
GO TO Foo
.</lang>
.</syntaxhighlight>


A <code>GO TO</code> can take a <code>DEPENDING ON</code> clause which will cause program flow to go to a certain paragraph/section depending on a certain value.
A <code>GO TO</code> can take a <code>DEPENDING ON</code> clause which will cause program flow to go to a certain paragraph/section depending on a certain value.
<lang cobol> GO TO First-Thing Second-Thing Third-Thing
<syntaxhighlight lang="cobol"> GO TO First-Thing Second-Thing Third-Thing
DEPENDING ON Thing-To-Do
DEPENDING ON Thing-To-Do


* *> Handle invalid thing...</lang>
* *> Handle invalid thing...</syntaxhighlight>
The previous example is equivalent to:
The previous example is equivalent to:
<lang cobol> EVALUATE Thing-To-Do
<syntaxhighlight lang="cobol"> EVALUATE Thing-To-Do
WHEN 1
WHEN 1
* *> Do first thing...
* *> Do first thing...
Line 566: Line 605:
WHEN OTHER
WHEN OTHER
* *> Handle invalid thing...
* *> Handle invalid thing...
END-EVALUATE</lang>
END-EVALUATE</syntaxhighlight>


=== ALTER ===
=== ALTER ===
Line 578: Line 617:


{{works with|GnuCOBOL}}
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
identification division.
program-id. altering.
program-id. altering.
Line 617: Line 656:
*> fall through to the exit
*> fall through to the exit
exit program.
exit program.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 631: Line 670:
=== PERFORM ===
=== PERFORM ===
The <code>PERFORM</code> statement can be used to transfer program flow to the specified sections/paragraphs in the subprogram, with control being returned when the end of the last paragraph/section or a relevant <code>EXIT</code> statement is reached.
The <code>PERFORM</code> statement can be used to transfer program flow to the specified sections/paragraphs in the subprogram, with control being returned when the end of the last paragraph/section or a relevant <code>EXIT</code> statement is reached.
<lang cobol> PROGRAM-ID. Perform-Example.
<syntaxhighlight lang="cobol"> PROGRAM-ID. Perform-Example.


PROCEDURE DIVISION.
PROCEDURE DIVISION.
Line 653: Line 692:
Moo.
Moo.
DISPLAY "Moo"
DISPLAY "Moo"
.</lang>
.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 666: Line 705:
=={{header|Comal}}==
=={{header|Comal}}==
===Call a procedure===
===Call a procedure===
<lang Comal>myprocedure
<syntaxhighlight lang="comal">myprocedure
END // End of main program
END // End of main program
PROC myprocedure
PROC myprocedure
PRINT "Hello, this is a procedure"
PRINT "Hello, this is a procedure"
ENDPROC myprocedure</lang>
ENDPROC myprocedure</syntaxhighlight>


===Exit a loop===
===Exit a loop===
<lang Comal>LOOP
<syntaxhighlight lang="comal">LOOP
PRINT "I'm in a loop!"
PRINT "I'm in a loop!"
EXIT
EXIT
ENDLOOP
ENDLOOP
PRINT "But i somehow got out of it."</lang>
PRINT "But i somehow got out of it."</syntaxhighlight>


===Conditional exit===
===Conditional exit===
<lang Comal>PRINT "I'm in a loop!"
<syntaxhighlight lang="comal">PRINT "I'm in a loop!"
LOOP
LOOP
INPUT "Do you want to exit?":answer$
INPUT "Do you want to exit?":answer$
EXIT WHEN answer$="y"
EXIT WHEN answer$="y"
ENDLOOP
ENDLOOP
PRINT "You got out of it."</lang>
PRINT "You got out of it."</syntaxhighlight>


===Goto===
===Goto===
<lang Comal>PRINT "Hello world"
<syntaxhighlight lang="comal">PRINT "Hello world"
GOTO label
GOTO label
PRINT "This line will never be output"
PRINT "This line will never be output"
label:
label:
PRINT "This program will end thanks to the evil GOTO statement"
PRINT "This program will end thanks to the evil GOTO statement"
END</lang>
END</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
=== goto ===
=== goto ===
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 703: Line 742:
writeln("I'm in your infinite loop.");
writeln("I'm in your infinite loop.");
goto label1;
goto label1;
}</lang>
}</syntaxhighlight>


=== Exceptions ===
=== Exceptions ===
D supports the try/catch/finally mechanism:
D supports the try/catch/finally mechanism:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


class DerivedException : Exception {
class DerivedException : Exception {
Line 728: Line 767:
writeln("finished (exception or none).");
writeln("finished (exception or none).");
}
}
}</lang>
}</syntaxhighlight>


=== Scope guards ===
=== Scope guards ===
Line 736: Line 775:


For instance:
For instance:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main(string[] args) {
void main(string[] args) {
Line 748: Line 787:
writeln("Gone, but we passed the first" ~
writeln("Gone, but we passed the first" ~
" chance to throw an exception.");
" chance to throw an exception.");
}</lang>
}</syntaxhighlight>


If the exception is thrown, then the only text that is written to the screen is "gone". If no exception is thrown, both calls to writeln occur.
If the exception is thrown, then the only text that is written to the screen is "gone". If no exception is thrown, both calls to writeln occur.
Line 771: Line 810:


[[Category:E examples needing attention]] <!-- Needs runnable examples, description of escape-catch, and maybe links to other flow control pages -->
[[Category:E examples needing attention]] <!-- Needs runnable examples, description of escape-catch, and maybe links to other flow control pages -->

=={{header|EasyLang}}==

With '''break <n>''' you can break out of a nested loop

<syntaxhighlight>
sum = 80036
for i = 0 to 50
for j = 0 to 50
if i * i + j * j * j = sum
print i & "² + " & j & "³ = " & sum
break 2
.
.
.
</syntaxhighlight>
{{out}}
<pre>
23² + 43³ = 80036
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 778: Line 837:
===CATCH-THROW===
===CATCH-THROW===
Some Forth implementations have goto, but not the standard. It does have an exception mechanism.
Some Forth implementations have goto, but not the standard. It does have an exception mechanism.
<lang forth>: checked-array
<syntaxhighlight lang="forth">: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
DOES> ( i -- a+i )
Line 790: Line 849:


: safe-access ( i -- a[i] )
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;</lang>
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 799: Line 858:
A compiler may offer the "assigned GO TO" facility, with statements such as <code>ASSIGN 120 TO THENCE</code> scattered about: 120 is a statement label, not an integer, and any statement label may be assigned to variable THENCE (which is an integer variable) as execution proceeds. A relatively restrained usage would be to select the label of a suitable FORMAT statement to use in a READ or WRITE statement in place of a fixed label, without affecting the flow of control. But <code>GO TO THENCE</code> will cause a GO TO for the current address held in THENCE... Should you yield to temptations such as <code>THENCE = THENCE - 6</code> (treating it as an ordinary integer), a subsequent <code>GO TO THENCE</code> may end execution with an error message, or something else...
A compiler may offer the "assigned GO TO" facility, with statements such as <code>ASSIGN 120 TO THENCE</code> scattered about: 120 is a statement label, not an integer, and any statement label may be assigned to variable THENCE (which is an integer variable) as execution proceeds. A relatively restrained usage would be to select the label of a suitable FORMAT statement to use in a READ or WRITE statement in place of a fixed label, without affecting the flow of control. But <code>GO TO THENCE</code> will cause a GO TO for the current address held in THENCE... Should you yield to temptations such as <code>THENCE = THENCE - 6</code> (treating it as an ordinary integer), a subsequent <code>GO TO THENCE</code> may end execution with an error message, or something else...


Aside from facilitating the production of spaghetti code, this sort of behaviour actually can be put to a positive use to handle the situation where in a large programme there may be portions that could be employed from a number of locations, and one does not wish to repeat that code each time - apart from the tedium of punching additional cards, each replication would demand its own unique set of statement labels. Further, such replication increases the total code size and memory is limited... <lang Fortran> ...
Aside from facilitating the production of spaghetti code, this sort of behaviour actually can be put to a positive use to handle the situation where in a large programme there may be portions that could be employed from a number of locations, and one does not wish to repeat that code each time - apart from the tedium of punching additional cards, each replication would demand its own unique set of statement labels. Further, such replication increases the total code size and memory is limited... <syntaxhighlight lang="fortran"> ...
ASSIGN 1101 to WHENCE !Remember my return point.
ASSIGN 1101 to WHENCE !Remember my return point.
GO TO 1000 !Dive into a "subroutine"
GO TO 1000 !Dive into a "subroutine"
Line 810: Line 869:
Common code, far away.
Common code, far away.
1000 do something !This has all the context available.
1000 do something !This has all the context available.
GO TO WHENCE !Return whence I came.</lang>
GO TO WHENCE !Return whence I came.</syntaxhighlight>
Since Algol in the 1960s it has been possible to define a routine within a larger routine that has access to all the context of the larger routine and so can be a convenient service routine for it, but Fortran does not allow a subroutine (or function) to be defined within a larger subroutine, except for the arithmetic statement function. One must write separate subroutines and struggle over providing access to context via COMMON and parameters. However, F90 introduced the MODULE arrangement whereby a collection of variables may all be referenced by a group of subroutines in the module without each having COMMON statements in common. Further, it allows a subroutine (or function) to use the CONTAINS feature, after which such a contained routine may be placed. Alas, it may not itself invoke CONTAINS even though Algol allows nesting as desired. And oddly, the contained routine must be at the ''end'' of the containing routine. So much for definition before usage. With such a facility, the possibility arises of perpetrating a GO TO from a contained routine to somewhere in its parent, however the F90 compilers are required to disallow access to outside labels, even those of FORMAT statements - rather a pity for that. Such escapes would have to copy whatever de-allocation steps were needed for a normal exit, which is simple enough on a stack-oriented design such as the B6700. However, its Algol compiler rejected attempts to jump from one routine ''into'' another (!) with the message "Bad GOTO. Too bad." Assembler programmers can do what they want, but for once, Fortran's designers show some restraint.
Since Algol in the 1960s it has been possible to define a routine within a larger routine that has access to all the context of the larger routine and so can be a convenient service routine for it, but Fortran does not allow a subroutine (or function) to be defined within a larger subroutine, except for the arithmetic statement function. One must write separate subroutines and struggle over providing access to context via COMMON and parameters. However, F90 introduced the MODULE arrangement whereby a collection of variables may all be referenced by a group of subroutines in the module without each having COMMON statements in common. Further, it allows a subroutine (or function) to use the CONTAINS feature, after which such a contained routine may be placed. Alas, it may not itself invoke CONTAINS even though Algol allows nesting as desired. And oddly, the contained routine must be at the ''end'' of the containing routine. So much for definition before usage. With such a facility, the possibility arises of perpetrating a GO TO from a contained routine to somewhere in its parent, however the F90 compilers are required to disallow access to outside labels, even those of FORMAT statements - rather a pity for that. Such escapes would have to copy whatever de-allocation steps were needed for a normal exit, which is simple enough on a stack-oriented design such as the B6700. However, its Algol compiler rejected attempts to jump from one routine ''into'' another (!) with the message "Bad GOTO. Too bad." Assembler programmers can do what they want, but for once, Fortran's designers show some restraint.


Once started on this path, many opportunities beckon: perhaps not just action "A" (achieved by "subroutine" 1000) is of use, there may be an action "B", and so on. One can then prepare the equivalent of a "to-do" list via something like<lang Fortran> ASSIGN 2000 TO WHENCE !Deviant "return" from 1000 to invoke 2000.
Once started on this path, many opportunities beckon: perhaps not just action "A" (achieved by "subroutine" 1000) is of use, there may be an action "B", and so on. One can then prepare the equivalent of a "to-do" list via something like<syntaxhighlight lang="fortran"> ASSIGN 2000 TO WHENCE !Deviant "return" from 1000 to invoke 2000.
ASSIGN 1103 TO THENCE !Desired return from 2000.
ASSIGN 1103 TO THENCE !Desired return from 2000.
GO TO 1000
GO TO 1000
1103 CONTINUE</lang>
1103 CONTINUE</syntaxhighlight>
So that "subroutine" 1000 would be invoked, which then invokes subroutine 2000, which returns via THENCE. And, instead of using simple variables such as THENCE and WHENCE, one could use an array and treat it like a stack... Those familiar with LISP or FORTH and similar languages will recognise a struggle to create new "verbs" from existing verbs, and their resulting usage in compound expressions. This is Philip Greenspun's "tenth" rule of programming.
So that "subroutine" 1000 would be invoked, which then invokes subroutine 2000, which returns via THENCE. And, instead of using simple variables such as THENCE and WHENCE, one could use an array and treat it like a stack... Those familiar with LISP or FORTH and similar languages will recognise a struggle to create new "verbs" from existing verbs, and their resulting usage in compound expressions. This is Philip Greenspun's "tenth" rule of programming.


Line 828: Line 887:


===Deviant RETURN===
===Deviant RETURN===
Similar possibilities arise with alternate returns from subroutines and functions, for instance to handle error conditions it might wish to report as with the READ statement. Thus, <code>CALL FRED(THIS,*123,*THENCE)</code> invokes a subroutine FRED with three parameters: THIS, then two oddities. The leading * (or &) signifies that these are no ordinary integers (or expressions) but instead are the labels of statements somewhere within the calling routine. Subroutine FRED might return in the normal way so that execution continues with the following statement, or, it may instead return with a GO TO for one of the labels...<lang Fortran> SUBROUTINE FRED(X,*,*) !With placeholders for unusual parameters.
Similar possibilities arise with alternate returns from subroutines and functions, for instance to handle error conditions it might wish to report as with the READ statement. Thus, <code>CALL FRED(THIS,*123,*THENCE)</code> invokes a subroutine FRED with three parameters: THIS, then two oddities. The leading * (or &) signifies that these are no ordinary integers (or expressions) but instead are the labels of statements somewhere within the calling routine. Subroutine FRED might return in the normal way so that execution continues with the following statement, or, it may instead return with a GO TO for one of the labels...<syntaxhighlight lang="fortran"> SUBROUTINE FRED(X,*,*) !With placeholders for unusual parameters.
...
...
RETURN !Normal return from FRED.
RETURN !Normal return from FRED.
...
...
RETURN 2 !Return to the second label.
RETURN 2 !Return to the second label.
END</lang>
END</syntaxhighlight>
More delicate souls prefer to see an integer parameter whose value will be set by FRED according to the desired condition, and every call to FRED would be followed by a computed GO TO on that value. Except that this statement is also disapproved of, so one is encouraged to code IF, or CASE, ''etc.'' and enjoy the repetition.
More delicate souls prefer to see an integer parameter whose value will be set by FRED according to the desired condition, and every call to FRED would be followed by a computed GO TO on that value. Except that this statement is also disapproved of, so one is encouraged to code IF, or CASE, ''etc.'' and enjoy the repetition.


Line 843: Line 902:
Similarly to escaping from a subroutine, within a DO-loop, a GO TO might jump out of the loop(s) - perhaps for good reason. More interesting is the possibility of jumping ''into'' a DO-loop's scope, possibly after jumping out - who knows what its index variable might have been changed to. This is considered poor form by others not writing such code and some compilers will reject any attempts. With the F77 introduction of IF ... THEN ... ELSE ... END IF constructions, jumping out of a block is still acceptable but jumping in is frowned on (even if only from the THEN clause to some part of its ELSE clause) and may be prevented.
Similarly to escaping from a subroutine, within a DO-loop, a GO TO might jump out of the loop(s) - perhaps for good reason. More interesting is the possibility of jumping ''into'' a DO-loop's scope, possibly after jumping out - who knows what its index variable might have been changed to. This is considered poor form by others not writing such code and some compilers will reject any attempts. With the F77 introduction of IF ... THEN ... ELSE ... END IF constructions, jumping out of a block is still acceptable but jumping in is frowned on (even if only from the THEN clause to some part of its ELSE clause) and may be prevented.


F90 offers a more decorous means for exiting DO-loops, including the additional DO WHILE loop, via the statements CYCLE and EXIT - the text "GO TO" does not appear as such, but the effect is the same. The CYCLE option means abandoning further statements within the block to test afresh the iteration condition, while EXIT means ending the iteration as if it had completed. Further syntax allows some compiler checking, as follows: <lang Fortran> XX:DO WHILE(condition)
F90 offers a more decorous means for exiting DO-loops, including the additional DO WHILE loop, via the statements CYCLE and EXIT - the text "GO TO" does not appear as such, but the effect is the same. The CYCLE option means abandoning further statements within the block to test afresh the iteration condition, while EXIT means ending the iteration as if it had completed. Further syntax allows some compiler checking, as follows: <syntaxhighlight lang="fortran"> XX:DO WHILE(condition)
statements...
statements...
NN:DO I = 1,N
NN:DO I = 1,N
Line 851: Line 910:
statements...
statements...
END DO NN
END DO NN
END DO XX </lang>
END DO XX </syntaxhighlight>
A DO-loop can be given a label such as XX (which is ''not'' in the numeric-only label area of fixed source format Fortran, and the syntax highlghter has missed yet another trick of Fortran syntax) and its corresponding END DO can be given a label also: the compiler checks that they match and some programmer errors might thereby be caught. With such labels in use, the CYCLE and EXIT statements can name the loop they are intended for, so that CYCLE NN steps to the next iteration for <code>I</code> (as if it were a GO TO the END DO having its label as a suffix) while the EXIT XX exits both the numeric DO-LOOP and the DO-WHILE loop - without such labels only the innermost loop is affected and one can lose track. These labels must not be the name of any other entity in the source, and specifically not the name of the variable of the DO-LOOP concerned. Thus, if there are many DO I = 1,N loops, each must have its own label. There is unfortunately no equivalent to <code>NEXT I</code> as in BASIC instead of <code>END DO</code>so as to be clear just which DO-LOOP is being ended and for which index variable.
A DO-loop can be given a label such as XX (which is ''not'' in the numeric-only label area of fixed source format Fortran, and the syntax highlghter has missed yet another trick of Fortran syntax) and its corresponding END DO can be given a label also: the compiler checks that they match and some programmer errors might thereby be caught. With such labels in use, the CYCLE and EXIT statements can name the loop they are intended for, so that CYCLE NN steps to the next iteration for <code>I</code> (as if it were a GO TO the END DO having its label as a suffix) while the EXIT XX exits both the numeric DO-LOOP and the DO-WHILE loop - without such labels only the innermost loop is affected and one can lose track. These labels must not be the name of any other entity in the source, and specifically not the name of the variable of the DO-LOOP concerned. Thus, if there are many DO I = 1,N loops, each must have its own label. There is unfortunately no equivalent to <code>NEXT I</code> as in BASIC instead of <code>END DO</code>so as to be clear just which DO-LOOP is being ended and for which index variable.


Line 876: Line 935:
Still, they are available when using the -lang qb dialect.
Still, they are available when using the -lang qb dialect.
This dialect provides the best support for the older QuickBASIC code.
This dialect provides the best support for the older QuickBASIC code.
<lang freebasic>
<syntaxhighlight lang="freebasic">
'$lang: "qb"
'$lang: "qb"


Line 891: Line 950:
Return
Return
Sleep
Sleep
</syntaxhighlight>
</lang>




=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=64e4e68b1c6ce73341d08ba2d9333c07 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=64e4e68b1c6ce73341d08ba2d9333c07 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
Dim siCount As Short


Line 906: Line 965:
Goto LoopIt
Goto LoopIt


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 920: Line 979:
===Goto===
===Goto===
Go has goto and labels. The following is an infinite loop:
Go has goto and labels. The following is an infinite loop:
<lang go>func main() {
<syntaxhighlight lang="go">func main() {
inf:
inf:
goto inf
goto inf
}</lang>
}</syntaxhighlight>
Gotos can jump forward or backward within a function but they have some restrictions. They cannot jump into any block from outside the block, and they cannot cause any variable to come into scope.
Gotos can jump forward or backward within a function but they have some restrictions. They cannot jump into any block from outside the block, and they cannot cause any variable to come into scope.


Line 932: Line 991:


The defer statement sets a function or method to be executed upon return from the enclosing function. This is useful when a function has multiple returns. The classic example is closing a file:
The defer statement sets a function or method to be executed upon return from the enclosing function. This is useful when a function has multiple returns. The classic example is closing a file:
<lang go>import "os"
<syntaxhighlight lang="go">import "os"


func processFile() {
func processFile() {
Line 949: Line 1,008:
// more processing
// more processing
// f.Close() will get called here too
// f.Close() will get called here too
}</lang>
}</syntaxhighlight>


===Goroutines===
===Goroutines===
Line 955: Line 1,014:


The following program prints a mix of 1’s and 0’s.
The following program prints a mix of 1’s and 0’s.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 970: Line 1,029:
fmt.Println("0")
fmt.Println("0")
}
}
}</lang>
}</syntaxhighlight>


A goroutine terminates upon return from the function called in the go statement. Unlike with a regular function call however, it cannot return a value--the calling goroutine has long continued and there is nothing waiting for a return value.
A goroutine terminates upon return from the function called in the go statement. Unlike with a regular function call however, it cannot return a value--the calling goroutine has long continued and there is nothing waiting for a return value.


Goroutines may not be able to communicate by returning values, but they have other ways. Principal is passing data through channels. Channel operations affect execution when they yield the processor, allowing other goroutines to run, but this does not normally alter flow of execution. The one exception is when channel operations are used in a select statement. A simple use,
Goroutines may not be able to communicate by returning values, but they have other ways. Principal is passing data through channels. Channel operations affect execution when they yield the processor, allowing other goroutines to run, but this does not normally alter flow of execution. The one exception is when channel operations are used in a select statement. A simple use,
<lang go>func answer(phone1, phone2 chan int) {
<syntaxhighlight lang="go">func answer(phone1, phone2 chan int) {
select {
select {
case <-phone1:
case <-phone1:
Line 982: Line 1,041:
// talk on phone two
// talk on phone two
}
}
}</lang>
}</syntaxhighlight>
Syntax is strongly reminiscent of the switch statement, but rules for flow control are very different. Select will block if no channel operation is possible. If one is possible, it will execute that case. If multiple operations are possible, it will pick one at random.
Syntax is strongly reminiscent of the switch statement, but rules for flow control are very different. Select will block if no channel operation is possible. If one is possible, it will execute that case. If multiple operations are possible, it will pick one at random.
===Process initialization===
===Process initialization===
Line 988: Line 1,047:


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 LET a=1
<syntaxhighlight lang="qbasic">10 LET a=1
20 IF a=2 THEN PRINT "This is a conditional statement"
20 IF a=2 THEN PRINT "This is a conditional statement"
30 IF a=1 THEN GOTO 50: REM a conditional jump
30 IF a=1 THEN GOTO 50: REM a conditional jump
Line 994: Line 1,053:
50 PRINT ("Hello" AND (1=2)): REM This does not print
50 PRINT ("Hello" AND (1=2)): REM This does not print
100 PRINT "Endless loop"
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump</lang>
110 GOTO 100:REM an unconditional jump</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,000: Line 1,059:
In the context of normal, functional-style code, there are no flow-control statements, because explicit flow control is imperative. A monad may offer flow control; what kinds are available depends on the monad. For example, the [http://haskell.org/haskellwiki/New_monads/MonadExit <code>ExitT</code> monad transformer] lets you use the <code>exitWith</code> function to jump out a block of statements at will.
In the context of normal, functional-style code, there are no flow-control statements, because explicit flow control is imperative. A monad may offer flow control; what kinds are available depends on the monad. For example, the [http://haskell.org/haskellwiki/New_monads/MonadExit <code>ExitT</code> monad transformer] lets you use the <code>exitWith</code> function to jump out a block of statements at will.


<lang haskell>import Control.Monad
<syntaxhighlight lang="haskell">import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans
import Control.Monad.Exit
import Control.Monad.Exit
Line 1,011: Line 1,070:
when (x == 3 && y == 2) $
when (x == 3 && y == 2) $
exitWith ()
exitWith ()
putStrLn "Done."</lang>
putStrLn "Done."</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
[http://www.HicEst.com More on HicEst's ALARM function]
[http://www.HicEst.com More on HicEst's ALARM function]
<lang hicest>1 GOTO 2 ! branch to label
<syntaxhighlight lang="hicest">1 GOTO 2 ! branch to label


2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3
2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3
Line 1,031: Line 1,090:
8 y = LOG( 0 , *9) ! on error branch to label 9
8 y = LOG( 0 , *9) ! on error branch to label 9


9 ALARM( 999 ) ! quit HicEst immediately</lang>
9 ALARM( 999 ) ! quit HicEst immediately</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 1,046: Line 1,105:
'''break expr'''<br>
'''break expr'''<br>
Default value of ''expr'' is the null value ''&amp;null''. This operator breaks out of the enclosing loop, yielding the expression as the result of the loop. Normally loops yield a failure ie no result, so you can write code like this:
Default value of ''expr'' is the null value ''&amp;null''. This operator breaks out of the enclosing loop, yielding the expression as the result of the loop. Normally loops yield a failure ie no result, so you can write code like this:
<lang icon>
<syntaxhighlight lang="icon">
if x := every i := 1 to *container do { # * is the 'length' operator
if x := every i := 1 to *container do { # * is the 'length' operator
if container[i] ~== y then
if container[i] ~== y then
Line 1,056: Line 1,115:
else
else
write("did not find an item")
write("did not find an item")
</syntaxhighlight>
</lang>
The expression given to ''break'' can be another ''break'', which effectively lets you break out of two levels of loop. Finally, the expression given to break can be the ''next'' command; for example
The expression given to ''break'' can be another ''break'', which effectively lets you break out of two levels of loop. Finally, the expression given to break can be the ''next'' command; for example
<lang icon>
<syntaxhighlight lang="icon">
break break next
break break next
</syntaxhighlight>
</lang>
breaks out of two levels of loop and re-enters the top of the third-level enclosing loop.
breaks out of two levels of loop and re-enters the top of the third-level enclosing loop.


Line 1,068: Line 1,127:
'''fail'''<br>
'''fail'''<br>
Causes the the enclosing procedure to terminate without returning value. This is different from returning void or a null value that many other languages do when the code does not return an actual value. For example, in
Causes the the enclosing procedure to terminate without returning value. This is different from returning void or a null value that many other languages do when the code does not return an actual value. For example, in
<lang icon>
<syntaxhighlight lang="icon">
x := ftn()
x := ftn()
</syntaxhighlight>
</lang>
The value of x will not be replaced if ftn() issues the ''fail'' command. If ftn fails, then Goal-Directed Evaluation will also fail the assignment, therefore x is not assigned a new value. If the flow of control through a procedure falls off the end, the procedure implicitly fails.
The value of x will not be replaced if ftn() issues the ''fail'' command. If ftn fails, then Goal-Directed Evaluation will also fail the assignment, therefore x is not assigned a new value. If the flow of control through a procedure falls off the end, the procedure implicitly fails.


Line 1,083: Line 1,142:
'''error trapping'''<br>
'''error trapping'''<br>
The keyword &amp;error is normally zero, but if set to a positive value, this sets the number of fatal errors that are tolerated and converted to expression failure; the value of &amp;error is decremented if this happens. Therefore the now-common TRY-CATCH behaviour can be written as:
The keyword &amp;error is normally zero, but if set to a positive value, this sets the number of fatal errors that are tolerated and converted to expression failure; the value of &amp;error is decremented if this happens. Therefore the now-common TRY-CATCH behaviour can be written as:
<lang icon>
<syntaxhighlight lang="icon">
&error := 1
&error := 1
mayErrorOut()
mayErrorOut()
Line 1,092: Line 1,151:
handleError(&errornumber, &errortext, &errorvalue) # keyword values containing facts about the failure
handleError(&errornumber, &errortext, &errorvalue) # keyword values containing facts about the failure
}
}
</syntaxhighlight>
</lang>
Various idiomatic simplifications can be applied depending on your needs.
Various idiomatic simplifications can be applied depending on your needs.


'''error throwing'''<br>
'''error throwing'''<br>
Errors can be thrown using the function
Errors can be thrown using the function
<lang icon>
<syntaxhighlight lang="icon">
runerr(errnumber, errorvalue) # choose an error number and supply the offending value
runerr(errnumber, errorvalue) # choose an error number and supply the offending value
</syntaxhighlight>
</lang>


=={{header|IDL}}==
=={{header|IDL}}==
Line 1,105: Line 1,164:
===goto===
===goto===


<lang idl>test:
<syntaxhighlight lang="idl">test:
..some code here
..some code here
goto, test</lang>
goto, test</syntaxhighlight>


(This is almost never used)
(This is almost never used)
Line 1,113: Line 1,172:
===on_error===
===on_error===


<lang idl>on_error, test</lang>
<syntaxhighlight lang="idl">on_error, test</syntaxhighlight>


(This resumes at the label <tt>test</tt> if an error is encountered)
(This resumes at the label <tt>test</tt> if an error is encountered)
Line 1,119: Line 1,178:
===on_ioerror===
===on_ioerror===


<lang idl>on_ioerror, test</lang>
<syntaxhighlight lang="idl">on_ioerror, test</syntaxhighlight>


(Same as <tt>on_error</tt>, but for EOFs and read-errors and such)
(Same as <tt>on_error</tt>, but for EOFs and read-errors and such)
Line 1,125: Line 1,184:
===break===
===break===


<lang idl>break</lang>
<syntaxhighlight lang="idl">break</syntaxhighlight>


immediately terminates the innermost current loop (or <tt>if</tt> or <tt>case</tt> etc)
immediately terminates the innermost current loop (or <tt>if</tt> or <tt>case</tt> etc)
Line 1,131: Line 1,190:
===continue===
===continue===


<lang idl>continue</lang>
<syntaxhighlight lang="idl">continue</syntaxhighlight>


immediately starts the next iteration of the current innermost loop
immediately starts the next iteration of the current innermost loop
Line 1,140: Line 1,199:


For example, here's an example of a program which loops over a sequence of integers, multiplying them by two (j's default prompt is 3 spaces, which makes line-at-a-time copy-and-paste simple, and the result here is displayed on the following line):
For example, here's an example of a program which loops over a sequence of integers, multiplying them by two (j's default prompt is 3 spaces, which makes line-at-a-time copy-and-paste simple, and the result here is displayed on the following line):
<lang j> 2 * 1 2 3
<syntaxhighlight lang="j"> 2 * 1 2 3
2 4 6</lang>
2 4 6</syntaxhighlight>


That said, J's control structures are documented at http://www.jsoftware.com/help/dictionary/ctrl.htm So, if you want to perform this same operation using a while loop, or a goto, you can do so. It's just... often not a good idea (but sometimes they are indispensable).
That said, J's control structures are documented at http://www.jsoftware.com/help/dictionary/ctrl.htm So, if you want to perform this same operation using a while loop, or a goto, you can do so. It's just... often not a good idea (but sometimes they are indispensable).
Line 1,153: Line 1,212:
The <tt>break</tt> statement can be used to terminate a <tt>case</tt> clause in a <tt>switch</tt> statement and to terminate a <tt>for</tt>, <tt>while</tt> or <tt>do-while</tt> loop. In loops, a <tt>break</tt> can be ''labeled'' or ''unlabeled''.
The <tt>break</tt> statement can be used to terminate a <tt>case</tt> clause in a <tt>switch</tt> statement and to terminate a <tt>for</tt>, <tt>while</tt> or <tt>do-while</tt> loop. In loops, a <tt>break</tt> can be ''labeled'' or ''unlabeled''.


<lang Java>switch (xx) {
<syntaxhighlight lang="java">switch (xx) {
case 1:
case 1:
case 2:
case 2:
Line 1,185: Line 1,244:
}
}
...
...
} while (thisCondition);</lang>
} while (thisCondition);</syntaxhighlight>


===continue===
===continue===
The <tt>continue</tt> statement skips the current iteration of a <tt>for</tt>, <tt>while</tt>, or <tt>do-while</tt> loop. As with <tt>break</tt> the <tt>continue</tt> statement can be ''labeled'' or ''unlabeled'' to allow iterating a loop level other than the current one in nested loops.
The <tt>continue</tt> statement skips the current iteration of a <tt>for</tt>, <tt>while</tt>, or <tt>do-while</tt> loop. As with <tt>break</tt> the <tt>continue</tt> statement can be ''labeled'' or ''unlabeled'' to allow iterating a loop level other than the current one in nested loops.


<lang Java>while (condition) {
<syntaxhighlight lang="java">while (condition) {
...
...
if (someCondition) { continue; /* skip to beginning of this loop */ }
if (someCondition) { continue; /* skip to beginning of this loop */ }
Line 1,214: Line 1,273:
}
}
....
....
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,233: Line 1,292:


Here is an example from the standard library:
Here is an example from the standard library:
<lang jq># Emit at most one item from the stream generated by g:
<syntaxhighlight lang="jq"># Emit at most one item from the stream generated by g:
def first(g): label $out | g | ., break $out;</lang>
def first(g): label $out | g | ., break $out;</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Julia provides the @goto and @label macros for goto within functions. In addition, the "break" keyword is used for jumping out of a single loop, throw() of an exception can be used to jump out of a try() statement's code, and the assert() and exit() functions can be used to terminate a program.
Julia provides the @goto and @label macros for goto within functions. In addition, the "break" keyword is used for jumping out of a single loop, throw() of an exception can be used to jump out of a try() statement's code, and the assert() and exit() functions can be used to terminate a program.
<lang julia>
<syntaxhighlight lang="julia">
function example()
function example()
println("Hello ")
println("Hello ")
Line 1,246: Line 1,305:
println("world")
println("world")
end
end
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 1,255: Line 1,314:


Here are some examples:
Here are some examples:
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,268: Line 1,327:
if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
println("Goodbye!") // won't be executed
println("Goodbye!") // won't be executed
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,283: Line 1,342:
=={{header|Lua}}==
=={{header|Lua}}==
Lua has the <code>break</code>-command to exit loops.
Lua has the <code>break</code>-command to exit loops.
<lang lua>i = 0
<syntaxhighlight lang="lua">i = 0
while true do
while true do
i = i + 1
i = i + 1
if i > 10 then break end
if i > 10 then break end
end</lang>
end</syntaxhighlight>
===Tail calls as GOTOs===
===Tail calls as GOTOs===
The following code - though obviously a useless infinite loop - will '''not''' cause a stack overflow:
The following code - though obviously a useless infinite loop - will '''not''' cause a stack overflow:
<lang lua>function func1 ()
<syntaxhighlight lang="lua">function func1 ()
return func2()
return func2()
end
end
Line 1,298: Line 1,357:
end
end


func1()</lang>
func1()</syntaxhighlight>
This is because Lua supports proper tail recursion. This means that because something being returned is necessarily the last action in a function, the interpreter treats a function call in this 'tail' position much like a GOTO in other languages and does not create a new stack level.
This is because Lua supports proper tail recursion. This means that because something being returned is necessarily the last action in a function, the interpreter treats a function call in this 'tail' position much like a GOTO in other languages and does not create a new stack level.

=={{header|M2000 Interpreter}}==
M2000 has labels, Goto, Gosub, On Goto, On Gosub, and can use numeric labels immediate at Then and Else clause. Goto can be used inside a block, or structure which may have hidden block. We can't use Goto to jump to outer module (calling module). Also we can't start a module from a label.

Gosub level controlled by Recursion.Limit (which is 10000 by default but we can change it to anything, like 1000000, using Recursion.limit 1000000), depends only from size of memory for 32bit applications (2Gbyte).

Every is a block structure for execution code synchronized by timer. If code exit execution time of block's constant time, executed later at same phase. There are three more statements for tasks, AFTER, THREAD and MAIN.TASK for executing code based on time in sequential of concurrent fashion, not shown here.

We can use Error "name of error" to produce error and we can catch it through a Try block.


====Use of Labels====
<syntaxhighlight lang="m2000 interpreter">
Module Inner {
long x=random(1, 2)
on x goto 90, 100
090 print "can print here if is "+x // if x=1
100 Print "ok"
gosub 500
alfa: // no statement here only comments because : is also statement separator
print "ok too"
integer c
Every 100 { // every 100 miliseconds this block executed
c++
gosub printc
if c>9 then 200
}
print "no print here"
200 Gosub exitUsingGoto
Every 100 { // every 100 miliseconds this block executed
c++
gosub printc
if c>19 then exit
}
gosub 500
try ok {
on x gosub 400, 1234
}
if ok else print error$ // sub not found (if x=2)
goto 1234 ' not exist so this is an exit from module
400 print "can print here if is "+x // if x=1
end
printc:
Print c
return
500 Print "exit from block using exit" : return
exitUsingGoto:
Print "exit from block using goto"
return
}
Inner
</syntaxhighlight>

====Use of Call Back function====
M2000 has no yield statement/function. We can use a call back function to get results, before a module exit. The call back function act as code in the calling module (has same scope), but has a difference: we can't use goto/gosub out of it

<syntaxhighlight lang="m2000 interpreter">
module outer {
static m as long=100 // if m not exist created
module count (&a(), b) {
long c=1
do
if b(c) then exit
call a(c)
c++
always
}
long z, i=100
// function k used as call back function, through lazy$()
function k {
read new i
print i // print 1 and 2
z+=i
m++
}
count lazy$(&k()), (lambda (i)->i>=3)
print z=3, i=100, m
}
clear // clear variables (and static variables) from this point
outer // m is 102
outer // m is 104
outer // m is 106
</syntaxhighlight>

====Using Break/Continue in Select Case====
Normally the Break statement break module (exit from module) or a Try { } block. Normally Continue is like exit in ordinary blocks or a new iteration for loop structures. For a Select case, a Break make the execution of other blocks from other cases to executed until "case else" or a continue statement. Both ends goes to end select. So break works in reverse of c's break. Without block { } in cases, Break and Continue works for the outer block (like normal break and continue). We can use Goto in cases, to exit select/end select structure, using or not using block in cases. Gosub can be used as usual everywhere.

<syntaxhighlight lang="m2000 interpreter">
Module checkSelect {
long m, i, k
for k=1 to 10
m=10
i=random(5, 10)
select case i
case <6
print "less than 6"
case 6
{
m++: break // break case block, and continue to next block
}
case 7
{
m++: break
}
case 8
{
m++: continue // exit after end select
}
case 9
print "is 9"
case else
print "more than 9"
end select
print m, i
next
}
checkSelect
</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Line 1,323: Line 1,502:


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
try
try
% do some stuff
% do some stuff
Line 1,329: Line 1,508:
% in case of error, continue here
% in case of error, continue here
end
end
</syntaxhighlight>
</lang>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* goto */
<syntaxhighlight lang="maxima">/* goto */
block(..., label, ..., go(label), ...);
block(..., label, ..., go(label), ...);


Line 1,339: Line 1,518:


/* error trapping */
/* error trapping */
errcatch(..., error("Bad luck!"), ...);</lang>
errcatch(..., error("Bad luck!"), ...);</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
===GOTO / G===
===GOTO / G===
<p>The GOTO command jumps to a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <lang MUMPS>GOTO LABEL^ROUTINE</lang>. This does not affect the subroutine stack, only the program pointer.</p><lang MUMPS>GOTO THERE</lang>
<p>The GOTO command jumps to a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <syntaxhighlight lang="mumps">GOTO LABEL^ROUTINE</syntaxhighlight>. This does not affect the subroutine stack, only the program pointer.</p><syntaxhighlight lang="mumps">GOTO THERE</syntaxhighlight>


===HALT / H===
===HALT / H===
<p>Halt and Hang have the same abbreviation, i.e. "H" but (as a mnemonic) Halt takes no arguments. Halt stops the current process, and clears all Locks and devices in Use.
<p>Halt and Hang have the same abbreviation, i.e. "H" but (as a mnemonic) Halt takes no arguments. Halt stops the current process, and clears all Locks and devices in Use.
On the Cache variant of MUMPS, there is a $HALT special variable that can be set, the value of the $HALT special variable is a routine that is called before cleaning up (in effect, a specialized final error trap).</p>
On the Cache variant of MUMPS, there is a $HALT special variable that can be set, the value of the $HALT special variable is a routine that is called before cleaning up (in effect, a specialized final error trap).</p>
<lang MUMPS> Read "Do you really wish to halt (Y/N)?",Q#1
<syntaxhighlight lang="mumps"> Read "Do you really wish to halt (Y/N)?",Q#1
IF Q="Y"!Q="y" HALT</lang>
IF Q="Y"!Q="y" HALT</syntaxhighlight>


===JOB / J===
===JOB / J===
<p> The JOB command starts another MUMPS job starting at a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <lang MUMPS>JOB LABEL^ROUTINE</lang>. <lang MUMPS>JOB THERE</lang> This does not affect the subroutine stack, nor the program pointer in the current job. Since MUMPS is a multi-processing (rather than multi-threading) language, the new job is independent of the current job.</p>
<p> The JOB command starts another MUMPS job starting at a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name. <syntaxhighlight lang="mumps">JOB LABEL^ROUTINE</syntaxhighlight>. <syntaxhighlight lang="mumps">JOB THERE</syntaxhighlight> This does not affect the subroutine stack, nor the program pointer in the current job. Since MUMPS is a multi-processing (rather than multi-threading) language, the new job is independent of the current job.</p>
<lang MUMPS> JOB LABEL^ROUTINE</lang>
<syntaxhighlight lang="mumps"> JOB LABEL^ROUTINE</syntaxhighlight>




===QUIT / Q===
===QUIT / Q===
<p>Exits a loop, or routine. It decreases the stack level. It can return a value to a calling routine if there is a value after it.</p><p>Quit is one of the commands that requires two spaces after it if it is followed in a line by more commands.</p>
<p>Exits a loop, or routine. It decreases the stack level. It can return a value to a calling routine if there is a value after it.</p><p>Quit is one of the commands that requires two spaces after it if it is followed in a line by more commands.</p>
<lang MUMPS>FOR I=1:1:1 QUIT:NoLoop DO YesLoop
<syntaxhighlight lang="mumps">FOR I=1:1:1 QUIT:NoLoop DO YesLoop
QUIT Returnvalue</lang>
QUIT Returnvalue</syntaxhighlight>
===XECUTE / X===
===XECUTE / X===
<p>eXecute acts as if it were a one line Do command. Its argument must be a string of valid MUMPS code, and it performs that code in a new stack level. There is an implied Quit at the end of each eXecute's argument string.</p><lang MUMPS> SET A="SET %=$INCREMENT(I)"
<p>eXecute acts as if it were a one line Do command. Its argument must be a string of valid MUMPS code, and it performs that code in a new stack level. There is an implied Quit at the end of each eXecute's argument string.</p><syntaxhighlight lang="mumps"> SET A="SET %=$INCREMENT(I)"
SET I=0
SET I=0
XECUTE A
XECUTE A
WRITE I</lang>
WRITE I</syntaxhighlight>
The above block will output "1".
The above block will output "1".
<math>Insert formula here</math>
<math>Insert formula here</math>
Line 1,381: Line 1,560:
The <tt>LEAVE</tt> instruction causes immediate exit from one or more <tt>DO</tt>, <tt>SELECT</tt> or <tt>LOOP</tt> constructs.
The <tt>LEAVE</tt> instruction causes immediate exit from one or more <tt>DO</tt>, <tt>SELECT</tt> or <tt>LOOP</tt> constructs.


<lang NetRexx>loop xx = 1 to 10
<syntaxhighlight lang="netrexx">loop xx = 1 to 10
if xx = 1 then leave -- loop terminated by leave
if xx = 1 then leave -- loop terminated by leave
say 'unreachable'
say 'unreachable'
end</lang>
end</syntaxhighlight>


A ''<tt>name</tt>'' parameter can be provided to direct <tt>LEAVE</tt> to a specific end of block (as defined by a <tt>LABEL</tt> option or in the case of a controlled <tt>LOOP</tt> the control variable of the loop.
A ''<tt>name</tt>'' parameter can be provided to direct <tt>LEAVE</tt> to a specific end of block (as defined by a <tt>LABEL</tt> option or in the case of a controlled <tt>LOOP</tt> the control variable of the loop.


<lang NetRexx>loop xx = 1 to 10 -- xx is the control variable
<syntaxhighlight lang="netrexx">loop xx = 1 to 10 -- xx is the control variable
...
...
loop yy = 1 to 10 -- yy is the control variable
loop yy = 1 to 10 -- yy is the control variable
Line 1,430: Line 1,609:
otherwise do; say 'nl selection'; say '...'; end
otherwise do; say 'nl selection'; say '...'; end
end selecting
end selecting
end vv</lang>
end vv</syntaxhighlight>


===ITERATE===
===ITERATE===
Line 1,437: Line 1,616:


As with <tt>LEAVE</tt> an optional ''<tt>name</tt>'' parameter can be supplied to direct the instruction to a loop level outside the current level.
As with <tt>LEAVE</tt> an optional ''<tt>name</tt>'' parameter can be supplied to direct the instruction to a loop level outside the current level.
<lang NetRexx>loop fff = 0 to 9
<syntaxhighlight lang="netrexx">loop fff = 0 to 9
...
...
loop xx = 1 to 3
loop xx = 1 to 3
Line 1,445: Line 1,624:
end
end
...
...
end fff</lang>
end fff</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
===Labeled Break & Continue===
===Labeled Break & Continue===
Break and continue can be used with block labels to jump out of multiple loops:
Break and continue can be used with block labels to jump out of multiple loops:
<lang nim>block outer:
<syntaxhighlight lang="nim">block outer:
for i in 0..1000:
for i in 0..1000:
for j in 0..1000:
for j in 0..1000:
if i + j == 3:
if i + j == 3:
break outer</lang>
break outer</syntaxhighlight>


===Try-Except-Finally===
===Try-Except-Finally===
<lang nim>var f = open "input.txt"
<syntaxhighlight lang="nim">var f = open "input.txt"
try:
try:
var s = readLine f
var s = readLine f
Line 1,463: Line 1,642:
echo "An error occurred!"
echo "An error occurred!"
finally:
finally:
close f</lang>
close f</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,469: Line 1,648:
An OCaml user can simulate flow control using exceptions:
An OCaml user can simulate flow control using exceptions:


<lang ocaml>exception Found of int
<syntaxhighlight lang="ocaml">exception Found of int


let () =
let () =
Line 1,478: Line 1,657:
print_endline "nothing found"
print_endline "nothing found"
with Found res ->
with Found res ->
Printf.printf "found %d\n" res</lang>
Printf.printf "found %d\n" res</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,485: Line 1,664:


break allows to break the current loop :
break allows to break the current loop :
<lang Oforth>break</lang>
<syntaxhighlight lang="oforth">break</syntaxhighlight>


continue allows to immediately start a new iteration :
continue allows to immediately start a new iteration :
<lang Oforth>continue</lang>
<syntaxhighlight lang="oforth">continue</syntaxhighlight>


perform is a method that transfer execution to the runnable on top of the stack, then returns :
perform is a method that transfer execution to the runnable on top of the stack, then returns :
<lang Oforth>perform</lang>
<syntaxhighlight lang="oforth">perform</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
Line 1,497: Line 1,676:


The <code>case</code> statement can be used for [[Pattern Matching]], but also like a switch statement in C:
The <code>case</code> statement can be used for [[Pattern Matching]], but also like a switch statement in C:
<lang oz>case {OS.rand} mod 3
<syntaxhighlight lang="oz">case {OS.rand} mod 3
of 0 then {Foo}
of 0 then {Foo}
[] 1 then {Bar}
[] 1 then {Bar}
[] 2 then {Buzz}
[] 2 then {Buzz}
end</lang>
end</syntaxhighlight>


The Lisp-influenced [http://www.mozart-oz.org/home/doc/loop/index.html for-loop] is very powerful and convenient to use.
The Lisp-influenced [http://www.mozart-oz.org/home/doc/loop/index.html for-loop] is very powerful and convenient to use.
Line 1,517: Line 1,696:
As an example for <code>choice</code>, a simple, but stupid way to solve the equation 2*X=18. We assume that the solution is somewhere in the interval 8-10, but we do not quite know what exactly it is.
As an example for <code>choice</code>, a simple, but stupid way to solve the equation 2*X=18. We assume that the solution is somewhere in the interval 8-10, but we do not quite know what exactly it is.


<lang oz>declare
<syntaxhighlight lang="oz">declare
proc {Stupid X}
proc {Stupid X}
choice
choice
Line 1,531: Line 1,710:
end
end
in
in
{Show {SearchOne Stupid}}</lang>
{Show {SearchOne Stupid}}</syntaxhighlight>


{{out}}
{{out}}
Line 1,546: Line 1,725:
=={{header|Pascal}}==
=={{header|Pascal}}==
===goto===
===goto===
<lang pascal>label
<syntaxhighlight lang="pascal">label
jumpto;
jumpto;
begin
begin
Line 1,555: Line 1,734:
goto jumpto;
goto jumpto;
...
...
end;</lang>
end;</syntaxhighlight>


===exception===
===exception===
<lang pascal>try
<syntaxhighlight lang="pascal">try
Z := DoDiv (X,Y);
Z := DoDiv (X,Y);
except
except
on EDivException do Z := 0;
on EDivException do Z := 0;
end;</lang>
end;</syntaxhighlight>


===Halt===
===Halt===
Halt stops program execution and returns control to the calling program. The optional argument
Halt stops program execution and returns control to the calling program. The optional argument
Errnum specifies an exit value. If omitted, zero is returned.
Errnum specifies an exit value. If omitted, zero is returned.
<lang pascal>procedure halt(errnum: Byte);</lang>
<syntaxhighlight lang="pascal">procedure halt(errnum: Byte);</syntaxhighlight>


===Exit===
===Exit===
Line 1,574: Line 1,753:
The optional argument X allows to specify a return value, in the case Exit
The optional argument X allows to specify a return value, in the case Exit
is invoked in a function. The function result will then be equal to X.
is invoked in a function. The function result will then be equal to X.
<lang pascal>procedure exit(const X: TAnyType)</lang>
<syntaxhighlight lang="pascal">procedure exit(const X: TAnyType)</syntaxhighlight>


Calls of functions/procedures as well as breaks and continues in loops are described in the corresponding tasks.
Calls of functions/procedures as well as breaks and continues in loops are described in the corresponding tasks.
Line 1,584: Line 1,763:
Goto is typically looked down upon by most Perl programmers
Goto is typically looked down upon by most Perl programmers


<lang perl>FORK:
<syntaxhighlight lang="perl">FORK:
# some code
# some code
goto FORK;</lang>
goto FORK;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Line 1,592: Line 1,771:
===goto===
===goto===
In 0.8.4+ Phix finally has a goto statement:
In 0.8.4+ Phix finally has a goto statement:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">p<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (no goto in JavaScript)</span>
<span style="color: #008080;">goto</span> <span style="color: #0000FF;">:<span style="color: #000000;">but_print</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"This will not be printed...\n"<span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">goto</span> <span style="color: #0000FF;">:</span><span style="color: #000000;">but_print</span>
<span style="color: #0000FF;">:<span style="color: #0000FF;">:<span style="color: #000000;">but_print</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"This will not be printed...\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"...but this will\n"<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">::</span><span style="color: #000000;">but_print</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"...but this will\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">p<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Imposing a self-policed rule that all jumps must be forward (or equivalently all backward, but never mixed) is recommended.
Imposing a self-policed rule that all jumps must be forward (or equivalently all backward, but never mixed) is recommended.


Line 1,615: Line 1,795:
Note that a goto statement, or inline assembly (a goto statement is implemented using fragments of auto-generated inline assembly) will cause the compiler to abandon certain optimisation efforts, in particular type inferencing and constant propagation, which can result in a larger and slower program.
Note that a goto statement, or inline assembly (a goto statement is implemented using fragments of auto-generated inline assembly) will cause the compiler to abandon certain optimisation efforts, in particular type inferencing and constant propagation, which can result in a larger and slower program.


Previous versions had no hll goto statement, however the folowing work around was (and still is) available:
Previous versions had no hll goto statement, however the following work around was (and still is) available:
<syntaxhighlight lang="phix">without js
<lang Phix>#ilASM{ jmp :label }
#ilASM{ jmp :label }
...
...
#ilASM{ ::label }</lang>
#ilASM{ ::label }</syntaxhighlight>
In top level code, label scope is restricted to a single ilASM construct,
In top level code, label scope is restricted to a single ilASM construct,
but within a routine, the scope is across all the ilasm in that routine.
but within a routine, the scope is across all the ilasm in that routine.
Line 1,627: Line 1,808:


It is also possible to declare global labels, which are superficially similar:
It is also possible to declare global labels, which are superficially similar:
<syntaxhighlight lang="phix">without js
<lang Phix>#ilASM{ call :%label }
#ilASM{ call :%label }
...
...
#ilASM{ jmp :skip
#ilASM{ jmp :skip
:%label
:%label
ret
ret
::skip }</lang>
::skip }</syntaxhighlight>
Global labels cannot be declared inside a routine, and as shown (almost always)
Global labels cannot be declared inside a routine, and as shown (almost always)
require a skip construct. It is up to the programmer to ensure global labels
require a skip construct. It is up to the programmer to ensure global labels
Line 1,645: Line 1,827:
a hll goto.
a hll goto.
&lt;/it was claimed&gt;
&lt;/it was claimed&gt;

===exit===
causes immediate termination of the immediately surrounding for or while loop, with control passing to the first statement after the loop, eg:
<!--<lang Phix>-->
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">x</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">location</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<!--</lang>-->


===continue===
===continue===
Personally I must agree with Douglas Crockford who says "I have never seen a piece of code that was not improved by refactoring it to remove the continue statement".<br>
Causes the next interation of the immediately surrounding loop to begin immediately, with any condition evaluated normally. The following two loops behave identically:
Causes the next interation of the immediately surrounding loop to begin immediately, with any condition evaluated normally. The following two loops behave identically:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">continue</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">continue</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">...</span>
<span style="color: #0000FF;">...</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">!=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">...</span>
<span style="color: #0000FF;">...</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


===return===
===exit===
causes immediate termination of the immediately surrounding for or while loop, with control passing to the first statement after the loop, eg:
Exits the current routine. Needs a value to return if used inside a function or type.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">x</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">location</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->


===break===
===break===
Terminate a switch statement. fallthrough is the opposite, overriding an implicit break between cases.
Terminate a switch statement. fallthrough is the opposite, overriding an implicit break between cases.<br>
Note that JavaScript uses break for both switch and loop constructs, therefore pwa/p2js imposes additional rules to ensure compatibility, ie sufficiently nested/anything JavaScript can do is fine, but while desktop/Phix allows a loop to directly exit a switch and vice versa, the transpiler terminates in error when it detects any such attempts.

===return===
Exits the current routine. Needs a value to return if used inside a function or type.


===abort, crash, throw===
===abort, crash, throw===
Line 1,685: Line 1,871:
Phix supports both multitasking and multithreading. In multitasking, at most one task is currently running, so no locking is
Phix supports both multitasking and multithreading. In multitasking, at most one task is currently running, so no locking is
required, and the application explicitly invokes task_yield to indicate when it is safe to switch between tasks. Multithreading
required, and the application explicitly invokes task_yield to indicate when it is safe to switch between tasks. Multithreading
is potentially much trickier, everything that could be accessed concurrently must be locked, however when one thread is stalled,
is potentially much trickier, everything that could be accessed concurrently must be locked - however when one thread is stalled,
perhaps waiting for a network response, the other threads are unaffected.
perhaps waiting for a network response, the other threads are unaffected.


Line 1,694: Line 1,880:
Introduced in PHP 5.3, PHP now has a goto flow-control structure, even though most PHP programmers see it as a bad habbit (may cause spaghetti-code).
Introduced in PHP 5.3, PHP now has a goto flow-control structure, even though most PHP programmers see it as a bad habbit (may cause spaghetti-code).


<lang php><?php
<syntaxhighlight lang="php"><?php
goto a;
goto a;
echo 'Foo';
echo 'Foo';
Line 1,700: Line 1,886:
a:
a:
echo 'Bar';
echo 'Bar';
?></lang>
?></syntaxhighlight>
{{out}}
{{out}}
<pre>Bar</pre>
<pre>Bar</pre>
Line 1,750: Line 1,936:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
LEAVE
LEAVE
The LEAVE statement terminates execution of a loop.
The LEAVE statement terminates execution of a loop.
Line 1,780: Line 1,966:
labelled statements. (This form is superseded by SELECT, above.)
labelled statements. (This form is superseded by SELECT, above.)
[GO TO can also be spelled as GOTO].
[GO TO can also be spelled as GOTO].
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 1,787: Line 1,973:
quitloop with argument exits from nested loops:
quitloop with argument exits from nested loops:


<lang pop11>while condition1 do
<syntaxhighlight lang="pop11">while condition1 do
while condition2 do
while condition2 do
if condition3 then
if condition3 then
Line 1,793: Line 1,979:
endif;
endif;
endwhile;
endwhile;
endwhile;</lang>
endwhile;</syntaxhighlight>


above quitloop(2) exits from both loops.
above quitloop(2) exits from both loops.
Line 1,802: Line 1,988:
nested loops:
nested loops:


<lang pop11>while condition1 do
<syntaxhighlight lang="pop11">while condition1 do
while condition2 do
while condition2 do
if condition3 then
if condition3 then
Line 1,809: Line 1,995:
endwhile;
endwhile;
endwhile;
endwhile;
l:;</lang>
l:;</syntaxhighlight>


Another use is to implement finite state machines:
Another use is to implement finite state machines:


<lang pop11>state1:
<syntaxhighlight lang="pop11">state1:
DO_SOMETHING();
DO_SOMETHING();
if condition1 then
if condition1 then
Line 1,828: Line 2,014:
...
...
stateN:
stateN:
....</lang>
....</syntaxhighlight>


Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure calls:
Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure calls:


<lang pop11>define outer();
<syntaxhighlight lang="pop11">define outer();
define inner(n);
define inner(n);
if n = 0 then
if n = 0 then
Line 1,841: Line 2,027:
inner(5);
inner(5);
final:;
final:;
enddefine;</lang>
enddefine;</syntaxhighlight>


This is useful to exit early from successful recursive search, and for exception handling.
This is useful to exit early from successful recursive search, and for exception handling.
Line 1,849: Line 2,035:
go_on is a multiway jump
go_on is a multiway jump


<lang pop11>go_on expression to lab1, lab2, ..., labN else elselab ;</lang>
<syntaxhighlight lang="pop11">go_on expression to lab1, lab2, ..., labN else elselab ;</syntaxhighlight>


If expression has value K the above will jump to label labK, if expression is not an integer, or if it outside 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).
If expression has value K the above will jump to label labK, if expression is not an integer, or if it outside 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).
Line 1,868: Line 2,054:
it is just:
it is just:


<lang pop11>return;</lang>
<syntaxhighlight lang="pop11">return;</syntaxhighlight>


but it is also possible to specify one or more return values:
but it is also possible to specify one or more return values:


<lang pop11>return(val1, val2, val3);</lang>
<syntaxhighlight lang="pop11">return(val1, val2, val3);</syntaxhighlight>


===chain===
===chain===
Line 1,878: Line 2,064:
chain has effect of "tail call" but is not necessarily in tail position. More precisely inside proc1.
chain has effect of "tail call" but is not necessarily in tail position. More precisely inside proc1.


<lang pop11>chain proc2(x1, x2, x3);</lang>
<syntaxhighlight lang="pop11">chain proc2(x1, x2, x3);</syntaxhighlight>


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.
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.
Line 1,887: Line 2,073:
===Goto===
===Goto===
Transfers control to the label referenced. It is not a safe way to exit loops.
Transfers control to the label referenced. It is not a safe way to exit loops.
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
top:
top:
i = i + 1
i = i + 1
Line 1,898: Line 2,084:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf </lang>
EndIf </syntaxhighlight>
===Gosub & Return===
===Gosub & Return===
Gosub stands for 'Go to sub routine'. A label must be specified after Gosub where the program execution continues and will do so until encountering a Return. When a return is reached, the program execution is then transferred immediately below the Gosub.
Gosub stands for 'Go to sub routine'. A label must be specified after Gosub where the program execution continues and will do so until encountering a Return. When a return is reached, the program execution is then transferred immediately below the Gosub.
Gosub is useful when building fast structured code with very low overhead.
Gosub is useful when building fast structured code with very low overhead.
<lang PureBasic>X=1: Y=2
<syntaxhighlight lang="purebasic">X=1: Y=2
Gosub Calc
Gosub Calc
;X will now equal 7
;X will now equal 7
Line 1,909: Line 2,095:
Calc:
Calc:
X+3*Y
X+3*Y
Return ; Returns to the point in the code where the Gosub jumped from</lang>
Return ; Returns to the point in the code where the Gosub jumped from</syntaxhighlight>
===FakeReturn===
===FakeReturn===
If the command Goto is used within the body of a sub routine, FakeReturn must be used to correct the stack or the program will crash.
If the command Goto is used within the body of a sub routine, FakeReturn must be used to correct the stack or the program will crash.
<lang PureBasic>Gosub MySub
<syntaxhighlight lang="purebasic">Gosub MySub


Lable2:
Lable2:
Line 1,923: Line 2,109:
Goto Lable2
Goto Lable2
EndIf
EndIf
Return</lang>
Return</syntaxhighlight>


===OnErrorGoto===
===OnErrorGoto===
This will transferee the program execution to the defined label if an error accrue.
This will transferee the program execution to the defined label if an error accrue.
<lang PureBasic>OnErrorGoto(?MyExitHandler)
<syntaxhighlight lang="purebasic">OnErrorGoto(?MyExitHandler)


X=1: Y=0
X=1: Y=0
Line 1,937: Line 2,123:
MyExitHandler:
MyExitHandler:
MessageRequester("Error", ErrorMessage())
MessageRequester("Error", ErrorMessage())
End</lang>
End</syntaxhighlight>
===OnErrorCall===
===OnErrorCall===
Similar to OnErrorGoto() but procedural instead.
Similar to OnErrorGoto() but procedural instead.
<lang PureBasic>Procedure MyErrorHandler()
<syntaxhighlight lang="purebasic">Procedure MyErrorHandler()
;All open files etc can be closed here
;All open files etc can be closed here
MessageRequester("Error", ErrorMessage())
MessageRequester("Error", ErrorMessage())
Line 1,949: Line 2,135:
X=1: Y=0
X=1: Y=0
Z= X/Y
Z= X/Y
;This line should never be reached</lang>
;This line should never be reached</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
===Loops===
===Loops===
Python supports ''break'' and ''continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
Python supports ''break'' and ''continue'' to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.
<lang python># Search for an odd factor of a using brute force:
<syntaxhighlight lang="python"># Search for an odd factor of a using brute force:
for i in range(n):
for i in range(n):
if (n%2) == 0:
if (n%2) == 0:
Line 1,963: Line 2,149:
else:
else:
result = None
result = None
print "No odd factors found"</lang>
print "No odd factors found"</syntaxhighlight>
In addition, as shown in the foregoing example, Python loops support an ''else:'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target. In that situation the ''else:'' suite can be used to handle the failure. (In most other languages one is forced to use a "sentinel value" or a special flag variable ... typically set to "False" before the loop and conditionally set to "True" within the loop to handle situations for which the Python ''else:'' on loops is intended).
In addition, as shown in the foregoing example, Python loops support an ''else:'' suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target. In that situation the ''else:'' suite can be used to handle the failure. (In most other languages one is forced to use a "sentinel value" or a special flag variable ... typically set to "False" before the loop and conditionally set to "True" within the loop to handle situations for which the Python ''else:'' on loops is intended).


Line 1,976: Line 2,162:
A custom Exception class is normally declared with the ''pass'' statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:
A custom Exception class is normally declared with the ''pass'' statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:


<lang python>class MyException(Exception): pass</lang>
<syntaxhighlight lang="python">class MyException(Exception): pass</syntaxhighlight>


One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.
One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.
Line 1,984: Line 2,170:
To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:
To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:


<lang python>class MyVirtual(object):
<syntaxhighlight lang="python">class MyVirtual(object):
def __init__(self):
def __init__(self):
raise NotImplementedError</lang>
raise NotImplementedError</syntaxhighlight>


It then becomes necessary for any descendants of this class to over-ride the ''__init__()'' method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.
It then becomes necessary for any descendants of this class to over-ride the ''__init__()'' method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.
Line 1,992: Line 2,178:


'''Case 1 - Try, Except'''
'''Case 1 - Try, Except'''
<lang python>try:
<syntaxhighlight lang="python">try:
temp = 0/0
temp = 0/0
# 'except' catches any errors that may have been raised between the code of 'try' and 'except'
# 'except' catches any errors that may have been raised between the code of 'try' and 'except'
except: # Note: catch all handler ... NOT RECOMMENDED
except: # Note: catch all handler ... NOT RECOMMENDED
print "An error occurred."
print "An error occurred."
# Output : "An error occurred"</lang>
# Output : "An error occurred"</syntaxhighlight>


'''Case 2 - Try, Except'''
'''Case 2 - Try, Except'''
<lang python>try:
<syntaxhighlight lang="python">try:
temp = 0/0
temp = 0/0
# here, 'except' catches a specific type of error raised within the try block.
# here, 'except' catches a specific type of error raised within the try block.
except ZeroDivisionError:
except ZeroDivisionError:
print "You've divided by zero!"
print "You've divided by zero!"
# Output : "You've divided by zero!"</lang>
# Output : "You've divided by zero!"</syntaxhighlight>


'''Case 3 - Try, Except, Finally'''
'''Case 3 - Try, Except, Finally'''
<lang python>try:
<syntaxhighlight lang="python">try:
temp = 0/0
temp = 0/0
except:
except:
Line 2,018: Line 2,204:
# Output :
# Output :
# An error occurred
# An error occurred
# End of 'try' block...</lang>
# End of 'try' block...</syntaxhighlight>


Note: Prior to version 2.5 a ''try:'' statement could contain either series of ''except:'' clauses '''or''' a ''finally:'' clause but '''not both.'''
Note: Prior to version 2.5 a ''try:'' statement could contain either series of ''except:'' clauses '''or''' a ''finally:'' clause but '''not both.'''
It was thus necessary to nest the exception handling in an enclosing ''try:''...''finally:'' loop like so:
It was thus necessary to nest the exception handling in an enclosing ''try:''...''finally:'' loop like so:


<lang python>try:
<syntaxhighlight lang="python">try:
try:
try:
pass
pass
Line 2,030: Line 2,216:
except SomeOtherException:
except SomeOtherException:
finally:
finally:
do_some_cleanup() # run in any case, whether any exceptions were thrown or not</lang>
do_some_cleanup() # run in any case, whether any exceptions were thrown or not</syntaxhighlight>


'''Case 4 - Try, Except, Else'''
'''Case 4 - Try, Except, Else'''
<lang python>try:
<syntaxhighlight lang="python">try:
temp = 1/1 # not a division by zero error
temp = 1/1 # not a division by zero error
except ZeroDivisionError: # so... it is not caught
except ZeroDivisionError: # so... it is not caught
Line 2,041: Line 2,227:
print "No apparent error occurred."
print "No apparent error occurred."
# Output :
# Output :
# No apparent error occurred.</lang>
# No apparent error occurred.</syntaxhighlight>


'''Case 5 - Try, Except, break, continue'''
'''Case 5 - Try, Except, break, continue'''
<lang python>i = 0
<syntaxhighlight lang="python">i = 0
while 1: # infinite loop
while 1: # infinite loop
try:
try:
Line 2,063: Line 2,249:
# Output :
# Output :
# You've divided by zero. Decrementing i and continuing...
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop</lang>
# Imaginary Number! Breaking out of loop</syntaxhighlight>


'''Case 6 - Creating your own custom exceptions, raise'''
'''Case 6 - Creating your own custom exceptions, raise'''
<lang python># Let's call our custom error "StupidError"; it inherits from the Exception class
<syntaxhighlight lang="python"># Let's call our custom error "StupidError"; it inherits from the Exception class


class StupidError(Exception): pass
class StupidError(Exception): pass
Line 2,078: Line 2,264:


# Output :
# Output :
# Something stupid occurred: Segfault</lang>
# Something stupid occurred: Segfault</syntaxhighlight>


===continue, else in "for" loop===
===continue, else in "for" loop===
<lang python> i = 101
<syntaxhighlight lang="python"> i = 101
for i in range(4): # loop 4 times
for i in range(4): # loop 4 times
print "I will always be seen."
print "I will always be seen."
Line 2,100: Line 2,286:
if(__name__ == "__main__"):
if(__name__ == "__main__"):
main()</lang>
main()</syntaxhighlight>


===The "with" statement===
===The "with" statement===
Line 2,106: Line 2,292:
See [[http://www.python.org/peps/pep-0343.html PEP 0343, The "with" statement]]
See [[http://www.python.org/peps/pep-0343.html PEP 0343, The "with" statement]]


<lang python>class Quitting(Exception): pass
<syntaxhighlight lang="python">class Quitting(Exception): pass
max = 10
max = 10
with open("some_file") as myfile:
with open("some_file") as myfile:
Line 2,114: Line 2,300:
if exit_counter > max:
if exit_counter > max:
raise Quitting
raise Quitting
print line,</lang>
print line,</syntaxhighlight>


The ''with'' statement allows classes to encapsulate "final" (clean-up) code which will automatically be executed regardless of exceptions that occur when working "with" these objects. Thus, for the foregoing example, the file will be closed regardless of whether it's more than 10 lines long. Many built-in and standard library classes have "context managers" which facilitate their use in ''with:'' code. In addition it's possible to define special __enter__() and __exit__() methods in one's own classes which will be implicitly called by the interpreter when an object is used within a ''with:'' statement.
The ''with'' statement allows classes to encapsulate "final" (clean-up) code which will automatically be executed regardless of exceptions that occur when working "with" these objects. Thus, for the foregoing example, the file will be closed regardless of whether it's more than 10 lines long. Many built-in and standard library classes have "context managers" which facilitate their use in ''with:'' code. In addition it's possible to define special __enter__() and __exit__() methods in one's own classes which will be implicitly called by the interpreter when an object is used within a ''with:'' statement.
Line 2,130: Line 2,316:
1
1


=={{header|Quackery}}==

A Quackery program is a dynamic array ('''''nest''''') of numbers (bigints) operators (opcodes or primitives) and nests (named or explicit). It is evaluated by a depth first traversal of the structure, placing numbers on a data stack, and keeping track of the evaluation with a return stack. Flow control is achieved with meta-control flow operators, which modify the return stack during evaluation. The naming convention for meta-control flow operators is to wrap them in reversed brackets. They are <code>]again[ ]done[ ]if[ ]iff[ ]else[ ]'[ ]do[ ]this[</code> and <code>]bailby[</code>.

The first five, <code>]done[ ]again[ ]if[ ]iff[ ]else[</code>, are used to create a mix and match set of control flow words.

<pre>
[ ]again[ ] is again
[ ]done[ ] is done
[ ]if[ ] is if
[ ]iff[ ] is iff
[ ]else[ ] is else</pre>

<code>again</code> causes evaluation of the current nest to start again.

<code>done</code> causes evaluation of the current nest to end, and evaluation of the calling nest to continue.

<code>if</code> conditionally skips over the next item in the nest being evaluated. (dependant on the top of the data stack; it skips if the TOS is zero, and does not skip if it is a non-zero number. If it is not a number evaluation halts and a problem is reported.

<code>iff</code> is like <code>if</code> but conditionally skips over the next two items. It combines with <code>else</code> (below) to form an if...else... construct, and with other words to form more control flow structures (below).

<code>else</code> unconditionally skips over the next item in the nest being evaluated.

Also provided are <code>until</code> and <code>while</code>, and the programmer can add more as desired.

<pre>[ not if ]again[ ] is until
[ not if ]done[ ] is while</pre>

As this is a mix and match word set, complex control-flow structures can be made, restricted only to single-point of entry, achieved by the intentional omission of a <code>go-to</code> operator. For example, this code fragment from the task [[Largest number divisible by its digits#Quackery|Largest number divisible by its digits]].
<pre> [ 504 -
dup digits
dup 5 has iff
drop again
dup 0 has iff
drop again
repeats if again ]</pre>

<code>' do this</code>enable first and higher order functions, and recursion. They are defined using meta control flow operators.
<pre>
[ ]'[ ] is '
[ ]do[ ] is do
[ ]this[ ] is this</pre>

<code>'</code> unconditionally skips over the next item in the current nest, and places (a pointer to) it on the data stack.

<code>do</code> evaluates the item on the top of the data stack.

<code>this</code> places (a pointer to) the nest currently being evaluated on the data stack. so, for example, the phrase <code>this do</code> will cause the nest containing the phrase to be evaluated recursively. For convenience, the word <code>recurse</code> is provided which does the same thing.

<pre>[ ]this[ do ] is recurse</pre>

For more complex recursive situations the words <code>this</code> and <code>do</code> can be deployed at different levels of nesting, and additionally a forward referencing mechanism is provided. This example is from the task [[Mutual recursion#Quackery|Mutual recursion]].
<pre> forward is f ( n --> n )

[ dup 0 = if done
dup 1 - recurse f - ] is m ( n --> n )
[ dup 0 = iff 1+ done
dup 1 - recurse m - ]
resolves f ( n --> n )</pre>

<code>]'[</code> and <code>do</code> are also used to create the iterative looping word <code>times</code>, which will repeat the next item in the nest a specified number of times. The index of the loop is available from the word <code>i^</code>, which counts up from zero with each iteration, and the word <code>i</code>, which counts down to zero. The index can be modified with the words <code>step</code>, which causes the index to be incremented by a specified number, <code>refresh</code>, which resets it to the originally specified number of iterations, and <code>conclude</code>, which will sets it to zero.

<code>times</code> is used in the definition of <code>witheach</code>, which iterates over a nest placing the next item in the nest on the data stack with each iteration, so <code>I^ I step refresh conclude</code> are available within <code>witheach</code> loops.
<pre> ' [ 10 11 12 13 14 15 16 17 18 19 ]
witheach
[ dup 14 > iff
[ drop conclude ] done
echo
say " is item number " i^ echo cr
2 step ]</pre>
{{out}}

<pre>10 is item number 0
12 is item number 2
14 is item number 4</pre>

<code>witheach</code> can be used to define [[Higher-order functions#Quackery|Higher-order functions]].

<code>]bail-by[</code> removes a specified number of returns from the return stack. This is a high risk activity, as the data stack and ancillary stacks used by <code>times</code> and others are not restored in the process, additionally many words add items to the return stack that need to be accounted for. Without proper precautions it is an effective way of causing unpredictable behaviour (usually crashing). It exists primarily for the backtracking provided by the words <code>backup</code>, <code>bail</code>, and <code>bailed</code>, which do take the proper precautions.


=={{header|Racket}}==
=={{header|Racket}}==
Line 2,138: Line 2,404:
Racket doesn't have a <tt>goto</tt>, but like other implementations of Scheme, it adopts the mantra of "Lambda: the Ultimate GOTO" by having all tail calls optimized. This allows writing code that is no different from your average assembly code -- for example, here's a direct translation of [[Greatest_common_divisor#x86_Assembly]] into a Racket function:
Racket doesn't have a <tt>goto</tt>, but like other implementations of Scheme, it adopts the mantra of "Lambda: the Ultimate GOTO" by having all tail calls optimized. This allows writing code that is no different from your average assembly code -- for example, here's a direct translation of [[Greatest_common_divisor#x86_Assembly]] into a Racket function:


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,159: Line 2,425:
(return %eax))
(return %eax))
(main))
(main))
</syntaxhighlight>
</lang>


=== Exceptions ===
=== Exceptions ===
Line 2,165: Line 2,431:
Racket has exceptions which are used in the usual way, and <tt>with-handlers</tt> to catch them. In fact, any value can be raised, not just exceptions. For example:
Racket has exceptions which are used in the usual way, and <tt>with-handlers</tt> to catch them. In fact, any value can be raised, not just exceptions. For example:


<lang racket>
<syntaxhighlight lang="racket">
(define (list-product l)
(define (list-product l)
(with-handlers ([void identity])
(with-handlers ([void identity])
Line 2,172: Line 2,438:
[(zero? (car l)) (raise 0)]
[(zero? (car l)) (raise 0)]
[else (loop (cdr l) (* r (car l)))]))))
[else (loop (cdr l) (* r (car l)))]))))
</syntaxhighlight>
</lang>


=== Continuations ===
=== Continuations ===
Line 2,190: Line 2,456:
Phasers are blocks that are transparent to the normal control flow but that are automatically called at an appropriate phase of compilation or execution. The current list of phasers may be found in [[https://design.raku.org/S04.html#Phasers S04/Phasers]].
Phasers are blocks that are transparent to the normal control flow but that are automatically called at an appropriate phase of compilation or execution. The current list of phasers may be found in [[https://design.raku.org/S04.html#Phasers S04/Phasers]].
===goto===
===goto===
<lang perl6>TOWN: goto TOWN;</lang>
<syntaxhighlight lang="raku" line>TOWN: goto TOWN;</syntaxhighlight>
Labels that have not been defined yet must be enclosed in quotes.
Labels that have not been defined yet must be enclosed in quotes.


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Flow Control"
Title: "Flow Control"
URL: http://rosettacode.org/wiki/Flow_Control_Structures
URL: http://rosettacode.org/wiki/Flow_Control_Structures
Line 2,261: Line 2,527:
print div 10 2
print div 10 2
print div 10 1
print div 10 1
print div 10 0</lang>
print div 10 0</syntaxhighlight>




Line 2,277: Line 2,543:


(Also, see '''function invocation''' and '''signal''' statement below.)
(Also, see '''function invocation''' and '''signal''' statement below.)
<lang rexx>call routineName /*no arguments passed to routine.*/
<syntaxhighlight lang="rexx">call routineName /*no arguments passed to routine.*/
call routineName 50 /*one argument (fifty) passed. */
call routineName 50 /*one argument (fifty) passed. */
call routineName 50,60 /*two arguments passed. */
call routineName 50,60 /*two arguments passed. */
Line 2,287: Line 2,553:
call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */
call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */
call date /*looks for DATE internally first*/
call date /*looks for DATE internally first*/
call 'DATE' /* " " " BIF | externally*/</lang>
call 'DATE' /* " " " BIF | externally*/</syntaxhighlight>
real-life example:
real-life example:
<lang rexx>numeric digits 1000 /*prepare for some gihugeic numbers.*/
<syntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
...
n=4
n=4
Line 2,301: Line 2,567:
!=!*j
!=!*j
end /*j*/
end /*j*/
return !</lang>
return !</syntaxhighlight>


===case===
===case===
Line 2,319: Line 2,585:


(Also, see the '''return''' statement below.)
(Also, see the '''return''' statement below.)
<lang rexx>exit
<syntaxhighlight lang="rexx">exit


exit expression</lang>
exit expression</syntaxhighlight>


===function invocation===
===function invocation===
Line 2,333: Line 2,599:


(Also, see the '''call''' statement above.)
(Also, see the '''call''' statement above.)
<lang rexx>numeric digits 1000 /*prepare for some gihugeic numbers.*/
<syntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
...
n=4
n=4
Line 2,344: Line 2,610:
!=!*j
!=!*j
end /*j*/
end /*j*/
return !</lang>
return !</syntaxhighlight>


===iterate===
===iterate===
Line 2,350: Line 2,616:


(All indentations in REXX are merely cosmetic and are used for readability.}
(All indentations in REXX are merely cosmetic and are used for readability.}
<lang rexx>sum=0
<syntaxhighlight lang="rexx">sum=0
do j=1 to 1000
do j=1 to 1000
if j//3==0 | j//7==0 then iterate
if j//3==0 | j//7==0 then iterate
Line 2,367: Line 2,633:
end /*m*/
end /*m*/
end /*k*/
end /*k*/
say 'prod=' prod</lang>
say 'prod=' prod</syntaxhighlight>


===go to===
===go to===
Line 2,374: Line 2,640:
===leave===
===leave===
The '''leave''' statement transfer control to the next REXX statement following the &nbsp; '''end''' &nbsp; statement of the current (active) &nbsp; '''do''' &nbsp; loop in which the '''leave''' statement is located. &nbsp; The '''leave''' statement can also specify which '''do''' loop is to be left (terminated) if the '''do''' loop has a named variable.
The '''leave''' statement transfer control to the next REXX statement following the &nbsp; '''end''' &nbsp; statement of the current (active) &nbsp; '''do''' &nbsp; loop in which the '''leave''' statement is located. &nbsp; The '''leave''' statement can also specify which '''do''' loop is to be left (terminated) if the '''do''' loop has a named variable.
<lang rexx> do j=1 to 10
<syntaxhighlight lang="rexx"> do j=1 to 10
say 'j=' j
say 'j=' j
if j>5 then leave
if j>5 then leave
Line 2,391: Line 2,657:
end /*m*/
end /*m*/
end /*k*/
end /*k*/
say 'sum=' sum</lang>
say 'sum=' sum</syntaxhighlight>


===raising conditions===
===raising conditions===
Line 2,402: Line 2,668:


(Also, see the '''signal''' statement below.)
(Also, see the '''signal''' statement below.)
<lang rexx>...
<syntaxhighlight lang="rexx">...
signal on syntax
signal on syntax
...
...
Line 2,433: Line 2,699:
say; say 'error code:' condition('D')
say; say 'error code:' condition('D')
say; say "Moral: don't do that."
say; say "Moral: don't do that."
exit 13</lang>
exit 13</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,466: Line 2,732:
following the instruction/command where the condition was encountered.
following the instruction/command where the condition was encountered.
<br>A short example:
<br>A short example:
<lang rexx>Say 'Interrupt this program after a short while'
<syntaxhighlight lang="rexx">Say 'Interrupt this program after a short while'
Call on halt
Call on halt
Do i=1 To 10000000
Do i=1 To 10000000
Line 2,472: Line 2,738:
End
End
halt: Say i j
halt: Say i j
Return</lang>
Return</syntaxhighlight>


===return===
===return===
Line 2,484: Line 2,750:


(Also, see the '''exit''' statement above.)
(Also, see the '''exit''' statement above.)
<lang rexx>return
<syntaxhighlight lang="rexx">return


return expression</lang>
return expression</syntaxhighlight>


===select===
===select===
The '''select''' statement is used to conditionally test for cases to selectively execute REXX statement(s).
The '''select''' statement is used to conditionally test for cases to selectively execute REXX statement(s).
<lang rexx>...
<syntaxhighlight lang="rexx">...
prod=1
prod=1
a=7 /*or somesuch.*/
a=7 /*or somesuch.*/
Line 2,511: Line 2,777:
end /*select*/
end /*select*/


say 'result for' a op b "=" r</lang>
say 'result for' a op b "=" r</syntaxhighlight>


===signal===
===signal===
Line 2,538: Line 2,804:


(Also, see '''raising conditions''' above.)
(Also, see '''raising conditions''' above.)
<lang rexx>...
<syntaxhighlight lang="rexx">...
signal on error
signal on error
signal on failure
signal on failure
Line 2,571: Line 2,837:
say; say 'REXX variable:' condition('D')
say; say 'REXX variable:' condition('D')
say; say "Moral: shouldn't do that."
say; say "Moral: shouldn't do that."
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,592: Line 2,858:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
i = 1
i = 1
while true
while true
Line 2,599: Line 2,865:
i = i + 1
i = i + 1
end
end
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 2,609: Line 2,875:
=== exceptions ===
=== exceptions ===
Use <code>raise</code> to throw an exception. You catch exceptions in the <code>rescue</code> clause of a <code>begin...end</code> block.
Use <code>raise</code> to throw an exception. You catch exceptions in the <code>rescue</code> clause of a <code>begin...end</code> block.
<lang ruby>begin
<syntaxhighlight lang="ruby">begin
# some code that may raise an exception
# some code that may raise an exception
rescue ExceptionClassA => a
rescue ExceptionClassA => a
Line 2,621: Line 2,887:
ensure
ensure
# execute this code always
# execute this code always
end</lang>
end</syntaxhighlight>
There is also a rescue modifier (example from the [http://www.pragprog.com/titles/ruby/programming-ruby Pickaxe book]):
There is also a rescue modifier (example from the [http://www.pragprog.com/titles/ruby/programming-ruby Pickaxe book]):
<lang ruby>values = ["1", "2.3", /pattern/]
<syntaxhighlight lang="ruby">values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]</lang>
# => [1, 2.3, "(?-mix:pattern)"]</syntaxhighlight>


=== catch and throw ===
=== catch and throw ===
<code>break</code> will only break out of a single level of loop. You can surround code in a catch block, and within the block you can throw a string or symbol to jump out to the end of the catch block (Ruby's GOTO, I suppose):
<code>break</code> will only break out of a single level of loop. You can surround code in a catch block, and within the block you can throw a string or symbol to jump out to the end of the catch block (Ruby's GOTO, I suppose):
<lang ruby>def some_method
<syntaxhighlight lang="ruby">def some_method
# ...
# ...
if some_condition
if some_condition
Line 2,645: Line 2,911:
end
end


puts "continuing after catching the throw"</lang>
puts "continuing after catching the throw"</syntaxhighlight>
=== yield ===
=== yield ===
<code>yield</code> passes control from the currently executing method to its code block.
<code>yield</code> passes control from the currently executing method to its code block.


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>/* GOTO: as in other languages
<syntaxhighlight lang="sas">/* GOTO: as in other languages
STOP: to stop current data step */
STOP: to stop current data step */
data _null_;
data _null_;
Line 2,690: Line 2,956:
8 44
8 44
;
;
run;</lang>
run;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
<lang Scala>import Goto._
<syntaxhighlight lang="scala">import Goto._
import scala.util.continuations._
import scala.util.continuations._


Line 2,719: Line 2,985:
}
}


}</lang>
}</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
===goto===
===goto===
<lang ruby>say "Hello"
<syntaxhighlight lang="ruby">say "Hello"
goto :world
goto :world
say "Never printed"
say "Never printed"
@:world
@:world
say "World"</lang>
say "World"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,737: Line 3,003:
=== Indirect absolute jump ===
=== Indirect absolute jump ===
The <tt>000 n to CI</tt> instruction loads the value stored at address <i>n</i> into the Current Instruction register. For instance,
The <tt>000 n to CI</tt> instruction loads the value stored at address <i>n</i> into the Current Instruction register. For instance,
<lang ssem>00101000000000000000000000000000 20 to CI
<syntaxhighlight lang="ssem">00101000000000000000000000000000 20 to CI
...
...
01010000000000000000000000000000 20. 10</lang>
01010000000000000000000000000000 20. 10</syntaxhighlight>
loads the number 10 into CI. Since CI is incremented <i>after</i> the instruction has been executed, rather than before, this fragment will cause execution to jump to address 11.
loads the number 10 into CI. Since CI is incremented <i>after</i> the instruction has been executed, rather than before, this fragment will cause execution to jump to address 11.


=== Indirect relative jump ===
=== Indirect relative jump ===
<tt>100 Add n to CI</tt> increases the number in the CI register by the value stored at address <i>n</i>.
<tt>100 Add n to CI</tt> increases the number in the CI register by the value stored at address <i>n</i>.
<lang ssem>00101000000001000000000000000000 Add 20 to CI
<syntaxhighlight lang="ssem">00101000000001000000000000000000 Add 20 to CI
...
...
01010000000000000000000000000000 20. 10</lang>
01010000000000000000000000000000 20. 10</syntaxhighlight>
adds 10 to CI. Once again, CI is incremented <i>after</i> the instruction has been executed: so the machine actually jumps ahead by 11 instructions.
adds 10 to CI. Once again, CI is incremented <i>after</i> the instruction has been executed: so the machine actually jumps ahead by 11 instructions.


Line 2,755: Line 3,021:
As an example, let's find a Pythagorean triple a,b,c such that a+b+c=n, where n is given. Here goto is used to break the two loops when such a triple is found. A '''[https://www.stata.com/help.cgi?m2_return return]''' can be used in such situations, unless one has to do further computations after the loop.
As an example, let's find a Pythagorean triple a,b,c such that a+b+c=n, where n is given. Here goto is used to break the two loops when such a triple is found. A '''[https://www.stata.com/help.cgi?m2_return return]''' can be used in such situations, unless one has to do further computations after the loop.


<lang stata>mata
<syntaxhighlight lang="stata">mata
function pythagorean_triple(n) {
function pythagorean_triple(n) {
for (a=1; a<=n; a++) {
for (a=1; a<=n; a++) {
Line 2,770: Line 3,036:


pythagorean_triple(1980)
pythagorean_triple(1980)
165 900 915</lang>
165 900 915</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 2,778: Line 3,044:
at some future time asynchronously, like this
at some future time asynchronously, like this


<lang tcl>after 1000 {myroutine x}</lang>
<syntaxhighlight lang="tcl">after 1000 {myroutine x}</syntaxhighlight>


which will call "<tt>myroutine</tt>" with parameter "<tt>x</tt>" 1000ms from 'now';
which will call "<tt>myroutine</tt>" with parameter "<tt>x</tt>" 1000ms from 'now';
Line 2,785: Line 3,051:
The scheduled task can be removed from the scheduler for example with
The scheduled task can be removed from the scheduler for example with


<lang tcl>after cancel myroutine</lang>
<syntaxhighlight lang="tcl">after cancel myroutine</syntaxhighlight>


(other ways are possible).
(other ways are possible).
Line 2,794: Line 3,060:
whose display is updated once a second:
whose display is updated once a second:


<lang tcl>package require Tk
<syntaxhighlight lang="tcl">package require Tk
proc update {} {
proc update {} {
.clockface configure -text [clock format [clock seconds]]
.clockface configure -text [clock format [clock seconds]]
Line 2,801: Line 3,067:
# now just create the 'clockface' and call ;update' once:
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
pack [label .clockface]
update</lang>
update</syntaxhighlight>


=== loop control ===
=== loop control ===
Line 2,808: Line 3,074:
=== exception ===
=== exception ===
Tcl's <code>catch</code> command can be used to provide a basic exception-handling mechanism:
Tcl's <code>catch</code> command can be used to provide a basic exception-handling mechanism:
<lang tcl>if {[catch { ''... code that might give error ...'' } result]} {
<syntaxhighlight lang="tcl">if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
puts "Error was $result"
} else {
} else {
''... process $result ...''
''... process $result ...''
}</lang>
}</syntaxhighlight>
Tcl 8.6 also has a <tt>try</tt>…<tt>trap</tt>…<tt>finally</tt> structure for more complex exception handling.
Tcl 8.6 also has a <tt>try</tt>…<tt>trap</tt>…<tt>finally</tt> structure for more complex exception handling.
<lang tcl>try {
<syntaxhighlight lang="tcl">try {
# Just a silly example...
# Just a silly example...
set f [open $filename]
set f [open $filename]
Line 2,823: Line 3,089:
} finally {
} finally {
close $f
close $f
}</lang>
}</syntaxhighlight>


=== custom control structures ===
=== custom control structures ===
A novel aspect of Tcl is that it's relatively easy to create new control structures (more detail at http://wiki.tcl.tk/685).
A novel aspect of Tcl is that it's relatively easy to create new control structures (more detail at http://wiki.tcl.tk/685).
For example, this example defines a command to perform some operation for each line of an input file:
For example, this example defines a command to perform some operation for each line of an input file:
<lang tcl>proc forfilelines {linevar filename code} {
<syntaxhighlight lang="tcl">proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
set filechan [open $filename]
Line 2,835: Line 3,101:
}
}
close $filechan
close $filechan
}</lang>
}</syntaxhighlight>
Now we can use it to print the length of each line of file "mydata.txt":
Now we can use it to print the length of each line of file "mydata.txt":
<lang tcl>forfilelines myline mydata.txt {
<syntaxhighlight lang="tcl">forfilelines myline mydata.txt {
puts [string length $myline]
puts [string length $myline]
}</lang>
}</syntaxhighlight>


=={{header|Tiny BASIC}}==
=={{header|Tiny BASIC}}==
<lang tinybasic> REM TinyBASIC has only two control flow structures: goto and gosub
<syntaxhighlight lang="tinybasic"> REM TinyBASIC has only two control flow structures: goto and gosub
LET N = 0
LET N = 0
10 LET N = N + 1
10 LET N = N + 1
Line 2,872: Line 3,138:
105 PRINT "55555"
105 PRINT "55555"
LET N = N + 1
LET N = N + 1
RETURN REM one return can serve several gosubs</lang>
RETURN REM one return can serve several gosubs</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 2,880: Line 3,146:
This skips the line that changes the value of x to 5.
This skips the line that changes the value of x to 5.


<lang vbnet> Sub bar2()
<syntaxhighlight lang="vbnet"> Sub bar2()
Dim x = 0
Dim x = 0
GoTo label
GoTo label
Line 2,886: Line 3,152:
label:
label:
Console.WriteLine(x)
Console.WriteLine(x)
End Sub</lang>
End Sub</syntaxhighlight>


=== On Error Goto ===
=== On Error Goto ===


This brances in the event of an error. Usually there is an Exit (Sub|Function) to seperate the normal code from the error handling code
This branches in the event of an error. Usually there is an Exit (Sub|Function) to separate the normal code from the error handling code


<lang vbnet> Sub foo()
<syntaxhighlight lang="vbnet"> Sub foo()
On Error GoTo label
On Error GoTo label
'do something dangerous
'do something dangerous
Line 2,898: Line 3,164:
label:
label:
Console.WriteLine("Operation Failed")
Console.WriteLine("Operation Failed")
End Sub</lang>
End Sub</syntaxhighlight>


''This style of code is rarely used.''
''This style of code is rarely used.''
Line 2,906: Line 3,172:
This performs a sequence of actions. If any action fails, the exception is discarded and next operation is performed.
This performs a sequence of actions. If any action fails, the exception is discarded and next operation is performed.


<lang vbnet>Sub foo2()
<syntaxhighlight lang="vbnet">Sub foo2()
On Error Resume Next
On Error Resume Next
Operation1()
Operation1()
Line 2,912: Line 3,178:
Operation3()
Operation3()
Operation4()
Operation4()
End Sub</lang>
End Sub</syntaxhighlight>


''This style of code is rarely used.''
''This style of code is rarely used.''
Line 2,920: Line 3,186:
This shows the classical and modern syntax for exiting a sub routine early.
This shows the classical and modern syntax for exiting a sub routine early.


<lang vbnet>Sub Foo1()
<syntaxhighlight lang="vbnet">Sub Foo1()
If Not WorkNeeded() Then Exit Sub
If Not WorkNeeded() Then Exit Sub
DoWork()
DoWork()
Line 2,928: Line 3,194:
If Not WorkNeeded() Then Return
If Not WorkNeeded() Then Return
DoWork()
DoWork()
End Sub</lang>
End Sub</syntaxhighlight>


=== Return value / Exit Function ===
=== Return value / Exit Function ===
Line 2,936: Line 3,202:
This variable is write-only.
This variable is write-only.


<lang vbnet>Function Foo3()
<syntaxhighlight lang="vbnet">Function Foo3()
Foo3 = CalculateValue()
Foo3 = CalculateValue()
If Not MoreWorkNeeded() Then Exit Function
If Not MoreWorkNeeded() Then Exit Function
Line 2,946: Line 3,212:
If Not MoreWorkNeeded() Then Return result
If Not MoreWorkNeeded() Then Return result
Return CalculateAnotherValue()
Return CalculateAnotherValue()
End Function</lang>
End Function</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Line 2,962: Line 3,228:


The following code demonstrates each of the above apart from '''Fiber.suspend''' which simply exits a CLI script.
The following code demonstrates each of the above apart from '''Fiber.suspend''' which simply exits a CLI script.
<lang ecmascript>var func = Fn.new { |n|
<syntaxhighlight lang="wren">var func = Fn.new { |n|
var i = 1
var i = 1
while (true) {
while (true) {
Line 2,978: Line 3,244:


var fiber = Fiber.new {
var fiber = Fiber.new {
Fiber.abort("Demo error") // error occcurred, abort script
Fiber.abort("Demo error") // error occurred, abort script
}
}


Line 2,984: Line 3,250:
for (n in a) {
for (n in a) {
func.call(n)
func.call(n)
if (n > 2) return // end module and hence the script as its a single module script
if (n > 2) return // end module and hence the script as it's a single module script
var error = fiber.try() // catch any error
var error = fiber.try() // catch any error
System.print("Caught error: " + error)
System.print("Caught error: " + error)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,998: Line 3,264:
</pre>
</pre>


=={{header|XPL0}}==
XPL0 does not have a ''goto'' statement, but it has other similar
statements. Its ''quit'' statement jumps out of a ''loop'' block. A
''return'' jumps out of a procedure, or a function where it's also used
to return the numerical result of the function. A ''return'' in the main
procedure terminates a program. An ''exit'' statement terminates a
program from any location. Like the ''return'' statement, it can send an
optional value, in this case to the operating system.

Some routines called ''intrinsics'' that are automatically included in a
program also affect flow control. The Abort intrinsic is like the
''exit'' statement except it does not return a value. (It's deprecated in
preference to ''exit''.) The Restart intrinsic, which can be called from
anywhere, restarts a program at its beginning. (The Rerun intrinsic is
used to distinguish a restart from a normal start.) Certain errors such
as divide-by-zero or attempting to open a non-existent file abort a
program. The Trap intrinsic can disable this feature. It's normally used
with the GetErr intrinsic, which provides a way to detect these kinds of
errors and handle them without aborting.


=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang yabasic>
<syntaxhighlight lang="yabasic">
gosub subrutina
gosub subrutina


Line 3,014: Line 3,299:
return
return
end
end
</syntaxhighlight>
</lang>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
===JP and JR===
<lang z80>JP &XXXX ; jump to an absolute address.
This is the equivalent of <code>GOTO</code> in BASIC, in that after the jump takes place, the CPU has no way of knowing where it came from.
JR &XX ; jump XX bytes forward or backward (this is a signed offset)
* <code>JP</code> takes three bytes, one for the jump itself, and two for the address. This instruction can jump conditionally based on the status of the zero, carry, sign, and overflow/parity flags. (On Game Boy, there are no sign or overflow/parity flags so those jumps won't work even for <code>JP</code>)
JR z,&XX ; conditionally jump forward or backward (JR cannot use parity, overflow, or sign flags to jump. JP, CALL, and RET can.

JP (HL) ; copy the value in HL to the program counter
* <code>JR</code> is a "short jump" that is program-counter relative. This instruction takes two bytes - one for the jump, and the second is an 8-bit signed offset. The offset represents how many bytes forward or backward to jump - <code>JR</code> can only travel forward 127 bytes and backward 128 bytes, and cannot branch based on the sign or overflow/parity flags - only zero and carry.
PUSH rr RET ; fake a return address and "return" to that address

CALL label ; call a subroutine named "label"
===Breaking out of a loop===
CALL z,label ; call a subroutine named "label" conditionally
A subroutine that loops is often escaped with a conditional return, or, if it needs to unwind the stack frame, a conditional jump to an unconditional return.
RET ; return from subroutine
<syntaxhighlight lang="z80">PrintString:
RET z ; return from subroutine conditionally
ld a,(hl) ;HL is our pointer to the string we want to print
DJNZ label ; decrement, jump if B nonzero to label
cp 0 ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read.
LDIR ; load, increment, repeat until BC = 0
LDDR ; load, decrement, repeat until BC = 0
ret z ;return if accumulator = zero
call PrintChar ;prints accumulator's ascii code to screen - on Amstrad CPC for example this label points to memory address &BB5A
CPIR ; compare, increment, repeat until BC = 0
CPDR ; compare, decrement, repeat until BC = 0
inc hl ;next char
jr PrintString ;jump back to the start of the loop. RET Z is our only exit.</syntaxhighlight>
OTIR ; out, increment, repeat until BC = 0

OTDR ; out, decrement, repeat until BC = 0
In the above example, the stack was never modified (besides the CALL pushing the return address) so <code>RET Z</code> was safe to use. Conditional returns are not safe to use if the stack needs to be unwound prior to exiting, since there's no way to conditionally unwind the stack without conditionally jumping to a section of code that does just that. In which case you don't need the return to be conditional anyway. This contrived example shows this in action.
INIR ; in, increment, repeat until BC = 0

INDR ; in, decrement, repeat until BC = 0
<syntaxhighlight lang="z80">foo:
RST # ; call a subroutine in low memory. This only takes 1 byte to encode (a CALL takes three.)</lang>
push af
bar:
ld a,(hl)
cp 255
jr z,exit
inc hl
jr bar

exit:
pop af
ret</syntaxhighlight>

===DJNZ===
<code>DJNZ</code> stands for "decrement, jump if nonzero." This is the equivalent of x86's <code>LOOP</code> command - as it subtracts 1 from the B register (just B, not BC) and if it's nonzero, jumps to a specified signed 8-bit offset. (It's better to use a label and let the assembler compute the offset for you.) Although this is usually used for looping, it can also jump forward. The same distance limits of <code>JR</code> apply to <code>DJNZ</code> as well. <code>DJNZ</code> cannot be made conditional based on flags, and it doesn't actually change the flags the same way <code>DEC B</code> would.

(Game Boy doesn't have this instruction - you'll have to use a combination of <code>DEC B</code> and <code>JR NZ</code>)


<syntaxhighlight lang="z80">loop:
In addition, there are multiple hardware interrupt modes. These are not directly controlled by the programmer, but the programmer needs to be aware of them so that they do not destroy the flow control of the program. At a minimum they should push all registers they use as soon as possible and pop them before returning (or alternatively use the exchange commands <code>EX AF,AF'</code> and <code>EXX</code> at the beginning and end.) What they do and which ones are used will vary depending on the hardware.
;your code goes here
DJNZ loop</syntaxhighlight>


===Block Instructions===
These instructions repeat until <code>BC</code> equals zero. They're useful for doing the same thing in a row, but have one-off equivalents that are faster. However, you can often save space by using these, especially if you can't hardcode a fixed repetition count before using one.


* <code>NMI</code> executes the instruction <code>CALL &0066</code> and is returned from with <code>RETN</code>. Unlike other interrupt modes, the <code>DI</code> instruction will not prevent it.
<code>LDIR</code> is the equivalent of <code>memcpy()</code> in C and <code>rep movsb</code> in x86. It loads from the address stored in HL and stores in the address pointed to by DE, increments both HL and DE, decrements BC, and repeats if BC doesn't equal zero.
* Interrupt mode 0 is selected with <code>IM 0</code>. The external hardware that generates the interrupt will do so by feeding the CPU the <code>CALL</code> instruction to the interrupt handler's memory location. This interrupt, and the other two below, should be returned from with <code>RETI</code>.
* Interrupt mode 1 is selected with <code>IM 1</code>. The external hardware that generates the interrupt will do so by feeding the CPU the instruction <code>RST 38</code>. This means that the interrupt handler (or a jump to it) will need to be located at memory address 0x0038.
* Interrupt mode 2 is selected with <code>IM 2</code>. This one is a bit weird. It uses the 8-bit value in the I register as well as am 8-bit value provided by whatever hardware is generating the interrupt, and will concatenate them into a memory address which will then be <code>CALL</code>ed. Generally, this interrupt mode is best handled by filling 257 bytes of memory with the same value, so that all interrupts addresses generated by this method are the same. Whatever address that will be is where the interrupt handler will go.


Essentially it's equivalent to the code below, except in the real <code>LDIR</code> the accumulator isn't actually altered in any way.
<syntaxhighlight lang="z80">_LDIR:
ld a,(hl)
ld (de),a
inc hl
inc de
dec bc
ld a,b
or c ;compare BC to zero
jr nz,_LDIR ;Game Boy doesn't have LDIR so you'll have to use this code instead.</syntaxhighlight>


There are several others that work in a similar fashion, such as:
(Side note: The Game Boy uses none of the above, its interrupts are handled differently. The only thing the Game Boy has in common with the Zilog Z80 is that interrupts will not occur if they were disabled with <code>DI</code>. The Game Boy has no NMI.)
* <code>LDDR</code> - equivalent of x86's <code>REP MOVSB</code> with direction flag set
* <code>CPIR</code> - equivalent of x86's <code>REPNZ SCASB</code> with direction flag clear
* <code>CPDR</code> - equivalent of x86's <code>REPNZ SCASB</code> with direction flag set
* <code>OTIR</code> - equivalent of x86's <code>REP OUTSB</code> with direction flag clear
* <code>OTDR</code> - equivalent of x86's <code>REP OUTSB</code> with direction flag set
* <code>INIR</code> - equivalent of x86's <code>REP INSB</code> with direction flag clear
* <code>INDR</code> - equivalent of x86's <code>REP INSB</code> with direction flag set


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>continue; continue(n); // continue nth nested loop
<syntaxhighlight lang="zkl">continue; continue(n); // continue nth nested loop
break; break(n); // break out of nth nested loop
break; break(n); // break out of nth nested loop
try{ ... }catch(exception){ ... } [else{ ... }]
try{ ... }catch(exception){ ... } [else{ ... }]
onExit(fcn); // run fcn when enclosing function exits</lang>
onExit(fcn); // run fcn when enclosing function exits</syntaxhighlight>
zkl has state machines for functional style stream processing. There are some special values that machines can return for flow control:
zkl has state machines for functional style stream processing. There are some special values that machines can return for flow control:
<pre>
<pre>
Line 3,065: Line 3,384:
</pre>
</pre>
As an example, decode URL strings:
As an example, decode URL strings:
<lang zkl>urlText.pump(String,
<syntaxhighlight lang="zkl">urlText.pump(String,
fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) },
fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) },
fcn(_,b,c){(b+c).toInt(16).toChar()})</lang>
fcn(_,b,c){(b+c).toInt(16).toChar()})</syntaxhighlight>
has two machines. The second machine only runs if "%" is seen.
has two machines. The second machine only runs if "%" is seen.
<lang zkl>urlText:="http%3A%2F%2Ffoo.com%2Fbar";
<syntaxhighlight lang="zkl">urlText:="http%3A%2F%2Ffoo.com%2Fbar";
urlText.pump(...).println();</lang>
urlText.pump(...).println();</syntaxhighlight>
{{out}}<pre>http://foo.com/bar</pre>
{{out}}<pre>http://foo.com/bar</pre>

Latest revision as of 15:31, 21 April 2024

Task
Flow-control structures
You are encouraged to solve this task according to the task description, using any language you may know.
Control Structures

These are examples of control structures. You may also be interested in:

Task

Document common flow-control structures.


One common example of a flow-control structure is the   goto   construct.

Note that   Conditional Structures   and   Loop Structures   have their own articles/categories.


Related tasks



11l

Translation of: Python

Loops

11l supports L.break and L.continue to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.

V n = 10
Int result

L(i) 0 .< n
   I (n % 2) == 0
      L.continue
   I (n % i) == 0
      result = i
      L.break
L.was_no_break
   result = -1
   print(‘No odd factors found’)

In addition, as shown in the foregoing example, 11l loops support an L.was_no_break suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target.

360 Assembly

Common 360 opcodes for flow-control structures:

Unconditional Branch (B)

To perform a 'goto'.

         B      TESTPX     goto label TESTPX
         BR     14         goto to the address found in register 14

Branch and Link (BAL)

To perform a 'call' to a subroutine. The first register at execution time is the next sequential address to allow a 'return'.

         LA     15,SINUSX  load in reg15 address of function SINUSX 
         BALR   14,15      call the subroutine SINUX and place address RETPNT in reg14
RETPNT   EQU    *
		 
SINUSX   EQU    *          subroutine SINUSX
         ...		 
         BR     14         return to caller

Conditional Branch (BC)

Fistly a compare instruction set the condition code (cc), secondly a conditional branch is performed.

         L      4,A        Load A in register 4
         C      4,B        Compare A with B
         BH     TESTGT     Branch on High        if A>B  then goto TESTGT
         BL     TESTLT     Branch on Low         if A<B  then goto TESTLT
         BE     TESTEQ     Branch on Equal       if A=B  then goto TESTEQ
         BNH    TESTLE     Branch on Not High    if A<=B then goto TESTLE
         BNL    TESTGE     Branch on Not Low     if A>=B then goto TESTGE
         BNE    TESTNE     Branch on Not Equal   if A<>B then goto TESTNE

Branch on Count (BCT)

To perform unconditional loops.

         LA     3,8                r3 loop counter
LOOP     EQU    *
         ...                       loop 8 times  (r3=8,7,...,2,1)
         BCT    3,LOOP             r3=r3-1 ; if r3<>0 then loop

Branch on Index (BX.)

BXLE to perform loops in old Fortran style with 3 registers.

*        do i=1 to 8 by 2
         L      3,1                r3 index and start value 1
         LA     4,2                r4 step 2
         L      5,8                r5 to value 8
LOOPI    EQU    *
         ...                       loop 4 times (r3=1,3,5,7)
         BXLE   3,4,LOOPI          r3=r3+r4; if r3<=r5 then loop

BXH to perform backward loops with 3 registers.

*        do i=8 to 1 by -2
         L      3,1                r3 index and start value 8
         LH     4,=H'-2'           r4 step -2
         L      5,8                r5 to value 1
LOOPI    EQU    *
         ...                       loop 4 times (r3=8,6,4,2)
         BXH    3,4,LOOPI          r3=r3+r4; if r3>r5 then loop

6502 Assembly

JMP

The jump instruction immediately jumps to any address:

		JMP $8000		;immediately JuMP to $8000 and begin executing
					;instructions there.

The indirect jump instruction immediately jumps to the address contained in the address:

		JMP ($8000)		;immediately JuMP to the address in memory locations
					;$8000 and $8001

JSR

The jump to subroutine instruction pushes the address of the next instruction minus one onto the stack and jumps to any address:

		JSR $8000	;Jump to SubRoutine

A return from subroutine instruction pops the return address off the stack, adds one, and jumps to that location:

		RTS		;ReTurn from Subroutine

NMI

This isn't a CPU instruction, it stands for Non-Maskable Interrupt. A non-maskable interrupt will push the program counter and the flags (in that order) then execute JMP ($FFFA), thereby reading the address stored there and jumping to that address. This interrupt cannot be disabled with SEI. The code at that address will need to end in RTI to properly return from the interrupt.

BRK

Similar to NMI, except the CPU executes execute JMP ($FFFE) instead. This is intended for debugging but is not of much practical use. Returning from this interrupt will skip the instruction after the BRK.

IRQ

This is a generic interrupt that jumps to the handler stored in memory location $FFFE, but unlike BRK it doesn't skip anything when it returns. This can be disabled with SEI, and often can be configured at runtime to occur upon specific events, unlike NMI which usually is triggered by the same event. Use RTI to return from this interrupt.

68000 Assembly

JMP,JSR,RTS, and branching work almost identical to 6502 Assembly. There are a few exceptions:

  • Compared to the 6502, BCS and BCC are the opposite for the purposes of unsigned comparisons. (The 6502 is actually the odd one out here - on most architectures "carry clear" represents greater than or equal, but 6502 is the opposite!)
  • An additional BSR can be used for nearby subroutines. This is quicker than a JSR but has a limited range. It is also not relocatable, in the sense that if you copy a routine to RAM that uses this instruction and try to execute it there, unless you also copied the routine that you're BSRing to, you're in for a nasty surprise. Many assemblers will auto-convert JSR to BSR and there's no easy way to conditionally stop that from happening except by inlining bytecode.
  • DBRA is used for looping. A register operand is decremented with each loop. The loop terminates when the value in the register underflows from 0 to 0xFFFF. As a result, the number of times you want to loop must be reduced by one. DBRA stands for "decrement, branch always" and there are other condition codes you can use, that will decrement the register operand (at word length) and branch unless the condition is met.
  • TRAP # is often used by the firmware to perform built-in tasks such as reading a keyboard or mouse input. Some systems (such as the Sega Genesis and NEO GEO) allow the programmer to alter the destination of the traps, allowing for custom error handlers. (However, these locations are usually in ROM and thus cannot be changed at runtime.)

Ada

goto

<<Top>>
   Put_Line("Hello, World");
   goto Top;

exit

Exit is used to break out of loops. Exit can be used with a label to break out of an inner loop to an outer loop and its enclosing outer loop:

Outer:
loop
   -- do something
   loop
      if Finished then
         exit Outer; -- exits both the inner and outer loops
      end if;
      -- do something else
   end loop;
end loop Outer;

or, more idiomatically,

Outer:
loop
   -- do something
   loop
      exit Outer when Finished;
      -- do something else
   end loop;
end loop Outer;

return

A procedure can be exited early, if there’s no more to be done.

procedure Foo is
begin
   --  do something
   if Nothing_More_To_Do then
      return;
   end if;
   --  do more
end Foo;

asynchronous transfer of control

A sequence of operation can be aborted with an asynchronous transfer of control to an alternative:

select
   delay 10.0;
   Put_Line ("Cannot finish this in 10s");
then abort
   -- do some lengthy calculation
   ...
end select;

The alternative can be a delay statement or else an entry point call followed by a sequence of operations. The statement blocks at the delay or entry call and executes the sequence of the operation introduced by then abort. If blocking is lifted before completion of the sequence, the sequence is aborted and the control is transferred there.

ALGOL 68

Works with: ALGOL 68 version Standard - except the Refinement Preprocessor is an extension
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

See also Exceptions to see how ALGOL 68 handles transput events.

One common use of a label in ALGOL 68 is to break out of nested loops.

(
   FOR j TO 1000 DO
     FOR i TO j-1 DO
       IF random > 0.999 THEN
         printf(($"Exited when: i="g(0)", j="g(0)l$,i,j));
         done
       FI
       # etc. #
     OD
   OD;
 done: EMPTY
);

Multi way jump using labels and EXIT to return result

STRING medal = (
  []PROC VOID award = (gold,silver,bronze);

  award[ 1 + ENTIER (random*3)];

  gold: "Gold" EXIT
  silver: "Silver" EXIT
  bronze: "Bronze"

);

print(("Medal awarded: ",medal, new line));

Another use is to implement finite state machines

STRING final state = (
  INT condition;
  PROC do something = VOID: condition := 1 + ENTIER (3 * random);
  
  state1:
     do something;
     CASE condition IN
        state 1, state 2
     OUT
        state n
     ESAC
  EXIT
  
  state 2:
     "State Two"
  EXIT
  
  state n:
     "State N"
);
print(("Final state: ",final state, new line));

ALGOL 68G implements a Refinement Preprocessor to aid with top down code development

# example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
determine first generation;
WHILE can represent next generation
DO calculate next generation;
   print next generation
OD.

determine first generation:
   INT previous := 1, current := 3.

can represent next generation:
   current <= max int - previous.

calculate next generation:
   INT new = current + previous;
   previous := current;
   current := new.

print next generation:
   printf (($lz","3z","3z","2z-d$, current,
            $xz","3z","3z","2z-d$, previous,
            $xd.n(real width - 1)d$, current / previous)).
Output:
Exited when: i=13, j=53
Medal awarded: Gold
Final state: State Two

             4              3 1.33333333333333
             7              4 1.75000000000000
            11              7 1.57142857142857
etc...

ALGOL W

As well as structured flow-control structures (loops, if-then-else, etc.) Algol W has a goto statement. A goto can lead out of the current procedure, which can be used for error handling. Goto can be written as "goto" or "go to".

begin
    integer i;
    integer procedure getNumber ;
    begin
        integer n;
        write( "n> " );
        read( i );
        if i< 0 then goto negativeNumber;
        i
    end getNumber ;

    i := getNumber;
    write( "positive or zero" );
    go to endProgram;
negativeNumber:
    writeon( "negative" );
endProgram:
end.

ARM Assembly

SWI n     ;software system call
B label   ;Branch. Just "B" is a branch always, but any condition code can be added for a conditional branch.
          ;In fact, almost any instruction can be made conditional to avoid branching.

BL label  ;Branch and Link. This is the equivalent of the CALL command on the x86 or Z80.
          ;The program counter is copied to the link register, then the operand of this command becomes the new program counter.

BX Rn     ;Branch and Exchange. The operand is a register. The program counter is swapped with the register specified.
          ;BX LR is commonly used to return from a subroutine.

addeq R0,R0,#1     ;almost any instruction can be made conditional. If the flag state doesn't match the condition code, the instruction
                   ;has no effect on registers or memory.

Arturo

return

return from the function currently being execute

loop control

Arturo's loop control statements are: break and continue

exceptions

Normally, in Arturo we'd use either try [...] or try? [...] else [...] blocks.

AutoHotkey

MsgBox, calling Label1
Gosub, Label1 
MsgBox, Label1 subroutine finished 
Goto Label2
MsgBox, calling Label2 ; this part is never reached
Return

Label1:
  MsgBox, Label1 
Return

Label2:
  MsgBox, Label2 will not return to calling routine
Return

AWK

The [awk] programming language is data driven. However, Awk has break and continue for loop control, as in C.

$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8


BASIC256

gosub subrutina

bucle:
print "Bucle infinito"
goto bucle


subrutina:
print "En subrutina"
pause 10
return
end


BBC BASIC

BBC BASIC has GOSUB and GOTO but they are deprecated.

      GOSUB subroutine
      
      (loop)
      PRINT "Infinite loop"
      GOTO loop
      END
      
      (subroutine)
      PRINT "In subroutine"
      WAIT 100
      RETURN

Bracmat

In Bracmat, the thing that comes closest to a GOTO construct is evaluation of a variable that contains some code, ending with an evaluation of the same variable. Due to tail recursion optimization this can run forever. Example:

  ( LOOP
  =   out$"Hi again!"
    & !LOOP
  )
& out$Hi!
& !LOOP
Output:
Hi!
Hi again!
Hi again!
Hi again!
...

C

goto

One common use of goto in C is to break out of nested loops.

int main()
{
  int i,j;
  for (j=1; j<1000; j++) {
    for (i=0; i<j, i++) {
      if (exit_early())
        goto out;
      /* etc. */
    }
  }
out:
  return 0;
}

C#

return

terminates the function and returns control to the caller.

int GetNumber() {
    return 5;
}

throw

throws (or rethrows) an exception. Control is transferred to the nearest catch block capable of catching the exception.
A finally block is always executed before control leaves the try block.

try {
    if (someCondition) {
        throw new Exception();
    }
} catch (Exception ex) {
    LogException(ex);
    throw;
} finally {
    cleanUp();
}

yield return and yield break

In a generator method, yield return causes the method to return elements one at a time. To make this work, the compiler creates a state machine behind the scenes. yield break terminates the iteration.

public static void Main() {
    foreach (int n in Numbers(i => i >= 2) {
        Console.WriteLine("Got " + n);
    }
}

IEnumerable<int> Numbers(Func<int, bool> predicate) {
    for (int i = 0; ; i++) {
        if (predicate(i)) yield break;
        Console.WriteLine("Yielding " + i);
        yield return i;
    }
}
Output:
Yielding 0
Got 0
Yielding 1
Got 1

await

is used to wait for an asynchronous operation (usually a Task) to complete. If the operation is already completed when await is encountered, the method will simply continue to execute. If the operation is not completed yet, the method will be suspended. A continuation will be set up to execute the rest of the method at a later time. Then, control will be returned to the caller.

async Task DoStuffAsync() {
    DoSomething();
    await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
    DoSomethingElse();
}

break and continue

continue causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.
break terminates the closest enclosing loop or switch statement. Control is passed to the statement that follows the terminated statement.

goto

goto Label; will cause control to jump to the statement with the corresponding label. This can be a case label inside a switch.
Because the label must be in scope, goto cannot jump inside of a loop.

while (conditionA) {
    for (int i = 0; i < 10; i++) {
        if (conditionB) goto NextSection;
        DoSomething(i);
    }
}
NextSection: DoOtherStuff();

C++

goto

Works with: GCC version 3.3.4
#include <iostream> 

int main()
{
 LOOP:
  std::cout << "Hello, World!\n";
 goto LOOP;
}

Note that "goto" may also be used in conjunction with other forms of branching.

Exceptions

Works with: GCC version 4.0.2

Exceptions are a way to give control back to a direct or indirect caller in case of an error. Note that throwing exceptions is usually very expensive, therefore they generally should only be used for exceptional situations.

#include <iostream>
#include <ostream>

void foo()
{
  std::cout << "Going to throw an exception.\n";
  throw 7; // almost any object can be thrown, including ints
  std::throw << "This output will never execute.\n";
}

void bar()
{
  std::cout << "Going to call foo().\n";
  foo();
  std::cout << "This will be skipped by the exception coming from foo.\n";
}

void baz()
{
  try // everything thrown from inside the following code block
  {   // will be covered by the following catch clauses
    std::cout << "Going to call bar().\n";
    bar();
    std::cout << "This will be skipped by the exception coming from foo.\n";
  }
  catch(...) // a simple catch-all, but doesn't give access to the thrown exception
  {
    std::cout << "An exception occured. I'll just throw it on.\n";
    throw; // without an argument, the caught exception is re-thrown
  }
  std::cout << "This will not be executed due to the re-throw in the catch block\n";
}

void foobar()
{
  try
  {
    baz();
  }
  catch(char const* s)
  {
    std::cout << "If foo had thrown a char const*, this code would be executed.\n";
    std::cout << "In that case, the thrown char const* would read " << s << ".\n";
  }
  catch(int i)
  {
    std::cout << "Caught an int, with value " << i << " (should be 7).\n";
    std::cout << "Not rethrowing the int.\n";
  }
  catch(...)
  {
    std::cout << "This catch-all doesn't get invoked because the catch(int) above\n"
              << "already took care of the exception (even if it had rethrown the\n"
              << "exception, this catch-all would not be invoked, because it's\n"
              << "only invoked for exceptions coming from the try block.\n";
  }
  std::cout << "This will be executed, since the exception was handled above, and not rethrown.\n";
}

int main()
{
  try
  {
    foobar();
  }
  catch(...)
  {
    std::cout << "The main function never sees the exception, because it's completely handled\n"
              << "inside foobar(). Thus this catch-all block never gets invoked.\n";
  }
}

COBOL

CALL

This transfers control to a subprogram, with control eventually being returned (provided the subprogram does not terminate the program).

CHAIN

This transfers control to the subprogram specified with no return of control. CHAIN is a non-standard extension created by Micro Focus and is found in Visual COBOL.

EXIT

EXIT takes a variety of clauses:

  • PARAGRAPH/PERFORM/SECTION: Control will be transferred immediately past the end of those blocks.
  • PERFORM CYCLE: The current iteration of the PERFORM will stop, and control will go to the clauses of the PERFORM which will determine if another iteration is to run.
  • PROGRAM: If used in a called function, execution of it is stopped and control returned to the calling program. If it is used in the main program, the statement is non-functional and ignored.

The PERFORM/PERFORM CYCLE clauses can only be used inside of an inline PERFORM statement.

GOBACK

If used in a called function, control will transferred back to the calling program. If it is used in the main program, the program will be terminated.

GO TO

Basic use:

       PROGRAM-ID. Go-To-Example.

       PROCEDURE DIVISION.
       Foo.
           DISPLAY "Just a reminder: GO TOs are evil."

           GO TO Foo
           .

A GO TO can take a DEPENDING ON clause which will cause program flow to go to a certain paragraph/section depending on a certain value.

       GO TO First-Thing Second-Thing Third-Thing
           DEPENDING ON Thing-To-Do

*      *> Handle invalid thing...

The previous example is equivalent to:

           EVALUATE Thing-To-Do
               WHEN 1
*                  *> Do first thing...

               WHEN 2
*                  *> Do second thing...

               WHEN 3
*                  *> Do third thing...

               WHEN OTHER
*                  *> Handle invalid thing...
           END-EVALUATE

ALTER

The much maligned altered GO.

The ALTER statement is now obsolete and not even mentioned in the COBOL 2014 standard.

If anyone wonders why this was ever designed into a language, you have to look back to the days of 8K RAM, multi-million dollar computers, and source code that was entered on punch cards, one line per card. Think of physically recoding an entire deck of punch cards (say even 6,000 lines worth) versus ALTERing a few paragraphs, that jump to new code at the end of the deck, and you may see one small reason why this was ever built into early versions of COBOL. Then ponder what the state of the code would be after three or four (or fifty) such patches, and then see why ALTER was deemed obsolete shortly after terminals and disk become the common way of entering programs.

Then pause to think about the fact that some COBOL code, written before ALTER went out of fashion, is still in production, to understand why it was implemented in GnuCOBOL, a relatively new COBOL dialect, still in development as of 2016 (along with other modern COBOL implementations, that support COBOL 2014, and yet continue to support language constructs that date all the way back to COBOL-60).

Works with: GnuCOBOL
       identification division.
       program-id. altering.

       procedure division.
       main section.

      *> And now for some altering.
       contrived.
       ALTER story TO PROCEED TO beginning
       GO TO story
       .

      *> Jump to a part of the story
       story.
       GO.
       .

      *> the first part
       beginning.
       ALTER story TO PROCEED to middle
       DISPLAY "This is the start of a changing story"
       GO TO story
       .

      *> the middle bit
       middle.
       ALTER story TO PROCEED to ending
       DISPLAY "The story progresses"
       GO TO story
       .

      *> the climatic finish
       ending.
       DISPLAY "The story ends, happily ever after"
       .

      *> fall through to the exit      
       exit program.
Output:
prompt$ cobc -xj altering.cob
This is the start of a changing story
The story progresses
The story ends, happily ever after

INVOKE

The INVOKE statement is used to transfer control to a method of a class/factory object.

PERFORM

The PERFORM statement can be used to transfer program flow to the specified sections/paragraphs in the subprogram, with control being returned when the end of the last paragraph/section or a relevant EXIT statement is reached.

       PROGRAM-ID. Perform-Example.

       PROCEDURE DIVISION.
       Main.
           PERFORM Moo
           PERFORM Display-Stuff
           PERFORM Boo THRU Moo

           GOBACK
           .

       Display-Stuff SECTION.
       Foo.
           DISPLAY "Foo " WITH NO ADVANCING
           .

       Boo.
           DISPLAY "Boo " WITH NO ADVANCING
           .

       Moo.
           DISPLAY "Moo"
           .
Output:
Moo
Foo Boo Moo
Boo Moo

STOP RUN

This immediately terminates the program.

Comal

Call a procedure

myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure

Exit a loop

LOOP
PRINT "I'm in a loop!"
EXIT
ENDLOOP
PRINT "But i somehow got out of it."

Conditional exit

PRINT "I'm in a loop!"
LOOP
INPUT "Do you want to exit?":answer$
EXIT WHEN answer$="y"
ENDLOOP
PRINT "You got out of it."

Goto

PRINT "Hello world"
GOTO label
PRINT "This line will never be output"
label:
PRINT "This program will end thanks to the evil GOTO statement"
END

D

goto

import std.stdio;

void main() {
    label1:
    writeln("I'm in your infinite loop.");
    goto label1;
}

Exceptions

D supports the try/catch/finally mechanism:

import std.stdio;

class DerivedException : Exception {
    this(string msg) { super(msg); }
}

void main(string[] args) {
    try {
        if (args[1] == "throw")
            throw new Exception("message");
    } catch (DerivedException ex) {
        // We never threw a DerivedException, so this
        // block is never called.
        writefln("caught derived exception %s", ex);
    } catch (Exception ex) {
        writefln("caught exception: %s", ex);
    } catch (Throwable ex) {
        writefln("caught throwable: %s", ex);
    } finally {
        writeln("finished (exception or none).");
    }
}

Scope guards

In a complex function, you might need to do cleanup in case of an exception, but it gets out of hand if there are many initialization steps that could fail. Scope guards offer a simplified syntax for try/finally.

There are three scopes you can listen for: exit, which is called unconditionally; failure, which is called if you leave the function via an exception; and success, which is called if you return from the function normally. A statement inside a scope block is only executed if execution reaches the scope block.

For instance:

import std.stdio;

void main(string[] args) {
    scope(exit)
        writeln("Gone");

    if (args[1] == "throw")
        throw new Exception("message");

    scope(exit)
        writeln("Gone, but we passed the first" ~
                " chance to throw an exception.");
}

If the exception is thrown, then the only text that is written to the screen is "gone". If no exception is thrown, both calls to writeln occur.

scope(failure) and scope(success) work similarly.

E

E does not have goto. The only primitive flow control construct which is not a loop, conditional, or exception is escape, or ejectors.

The basic syntax is

escape ej {
  ...body...
}

Within body variable ej then contains a one-argument function (an ejector) which, if called, immediately returns the provided value from the escape block.

This is a limited form of continuation (it cannot be used after the escape block exits).

Loop break, loop continue, and return-from-middle-of-function are all defined in terms of this basic construct.

EasyLang

With break <n> you can break out of a nested loop

sum = 80036
for i = 0 to 50
   for j = 0 to 50
      if i * i + j * j * j = sum
         print i & "² + " & j & "³ = " & sum
         break 2
      .
   .
.
Output:
23² + 43³ = 80036

Erlang

The one Erlang flow control structure, apart from the ones excluded in the task description, is Exceptions

Forth

CATCH-THROW

Some Forth implementations have goto, but not the standard. It does have an exception mechanism.

: checked-array
  CREATE ( size -- ) DUP , CELLS ALLOT
  DOES> ( i -- a+i )
    2DUP @ 0 SWAP WITHIN IF
      SWAP 1+ CELLS +
    ELSE
      1 THROW
    THEN ;

8 checked-array myarray

: safe-access ( i -- a[i] )
  ['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;

Fortran

The basic: GO TO label

Fortran offers GO TO label where label is a number, an integer, which is prefixed to some executable statement according to the rules of Fortran source layout. It is not considered to be a numerical value, though zero is not an allowed label and leading zero digits are ignored. Fortran has no reserved words and gives no significance to spaces, so that G O TO 12 3 4 is just as valid as GO TO 1234 and other usages. Text labels are not allowed, however a statement such as GO TO START is possible. Even so, "START" is not itself a label, but the name of a variable which is used in special ways - see the ASSIGN statement usage, below.

Elaborations on GO TO

A compiler may offer the "assigned GO TO" facility, with statements such as ASSIGN 120 TO THENCE scattered about: 120 is a statement label, not an integer, and any statement label may be assigned to variable THENCE (which is an integer variable) as execution proceeds. A relatively restrained usage would be to select the label of a suitable FORMAT statement to use in a READ or WRITE statement in place of a fixed label, without affecting the flow of control. But GO TO THENCE will cause a GO TO for the current address held in THENCE... Should you yield to temptations such as THENCE = THENCE - 6 (treating it as an ordinary integer), a subsequent GO TO THENCE may end execution with an error message, or something else...

Aside from facilitating the production of spaghetti code, this sort of behaviour actually can be put to a positive use to handle the situation where in a large programme there may be portions that could be employed from a number of locations, and one does not wish to repeat that code each time - apart from the tedium of punching additional cards, each replication would demand its own unique set of statement labels. Further, such replication increases the total code size and memory is limited...

      ...
      ASSIGN 1101 to WHENCE   !Remember my return point.
      GO TO 1000              !Dive into a "subroutine"
 1101 CONTINUE                !Resume.
      ... 
      ASSIGN 1102 to WHENCE   !Prepare for another invocation.
      GO TO 1000              !Like GOSUB in BASIC.
 1102 CONTINUE                !Carry on.
      ...
Common code, far away.
 1000 do something            !This has all the context available.
      GO TO WHENCE            !Return whence I came.

Since Algol in the 1960s it has been possible to define a routine within a larger routine that has access to all the context of the larger routine and so can be a convenient service routine for it, but Fortran does not allow a subroutine (or function) to be defined within a larger subroutine, except for the arithmetic statement function. One must write separate subroutines and struggle over providing access to context via COMMON and parameters. However, F90 introduced the MODULE arrangement whereby a collection of variables may all be referenced by a group of subroutines in the module without each having COMMON statements in common. Further, it allows a subroutine (or function) to use the CONTAINS feature, after which such a contained routine may be placed. Alas, it may not itself invoke CONTAINS even though Algol allows nesting as desired. And oddly, the contained routine must be at the end of the containing routine. So much for definition before usage. With such a facility, the possibility arises of perpetrating a GO TO from a contained routine to somewhere in its parent, however the F90 compilers are required to disallow access to outside labels, even those of FORMAT statements - rather a pity for that. Such escapes would have to copy whatever de-allocation steps were needed for a normal exit, which is simple enough on a stack-oriented design such as the B6700. However, its Algol compiler rejected attempts to jump from one routine into another (!) with the message "Bad GOTO. Too bad." Assembler programmers can do what they want, but for once, Fortran's designers show some restraint.

Once started on this path, many opportunities beckon: perhaps not just action "A" (achieved by "subroutine" 1000) is of use, there may be an action "B", and so on. One can then prepare the equivalent of a "to-do" list via something like

      ASSIGN 2000 TO WHENCE      !Deviant "return" from 1000 to invoke 2000.
      ASSIGN 1103 TO THENCE      !Desired return from 2000.
      GO TO 1000
 1103 CONTINUE

So that "subroutine" 1000 would be invoked, which then invokes subroutine 2000, which returns via THENCE. And, instead of using simple variables such as THENCE and WHENCE, one could use an array and treat it like a stack... Those familiar with LISP or FORTH and similar languages will recognise a struggle to create new "verbs" from existing verbs, and their resulting usage in compound expressions. This is Philip Greenspun's "tenth" rule of programming.

Another such usage would be to implement "coroutines", the classic example being to imagine a system that processes both Fortran statements and Fortran commentary, but each in their own way. After scanning some Fortran source, commentary is found so control flows to resume the commentary processing from where it had left off, then when further Fortran source is found, control flows back whence the Fortran source process left off. This is quite different from having subroutines FCODE and FCOMM which when invoked start at their start each time (as say when a new statement begins) rather than picking up where they left off because the switches occurred in the middle of a statement. Quite aside from questions of mutual recursion.

If one is good, more are better?

There is also a "computed GO TO" with syntax like GO TO (101,50,75,50), n where n is an integer variable (or expression) that selects from the list of statement labels: in this example if its value is three, then the third label, 75, will be selected. If the value is less than one or greater than the number of labels in the list, odd behaviour is likely, differing by compiler. Possibly by continuing with the next statement, or ending execution with an error message, or making a leap into the void. This statement can be used to produce a tangle as described for the ASSIGN facility, but is commonly used as a central direction station, or "dispatch table" for instance when a programme accepts an input which is one of a number of commands and after identifying it from a list of recognised commands (such as "List", "Dump", LineFit", "Quit", etc.), performs a computed GO TO to reach the portion that processes that command. Again, familiar to LISP programmers.

Escape from mishap

An implicit GO TO can appear in READ and WRITE statements (and a few others), that will be taken should there be certain difficulties. Thus READ (IN,6,END = 200, ERR = 300) STUFF reads input from I/O unit IN (an integer value) into variable STUFF according to the FORMAT statement labelled 6. But should there be instead an end-of-file, rather than ending execution with an error code, execution will GO TO label 200, while if there should arise some difficulty with the format of the incoming data (two decimal points in one data field, etc.) then execution will GO TO label 300. FORMAT statements, though labelled, are not considered suitable destinations for GO TO jumps.

Deviant RETURN

Similar possibilities arise with alternate returns from subroutines and functions, for instance to handle error conditions it might wish to report as with the READ statement. Thus, CALL FRED(THIS,*123,*THENCE) invokes a subroutine FRED with three parameters: THIS, then two oddities. The leading * (or &) signifies that these are no ordinary integers (or expressions) but instead are the labels of statements somewhere within the calling routine. Subroutine FRED might return in the normal way so that execution continues with the following statement, or, it may instead return with a GO TO for one of the labels...

      SUBROUTINE FRED(X,*,*)     !With placeholders for unusual parameters.
        ...
        RETURN          !Normal return from FRED.
        ...
        RETURN 2        !Return to the second label.
      END

More delicate souls prefer to see an integer parameter whose value will be set by FRED according to the desired condition, and every call to FRED would be followed by a computed GO TO on that value. Except that this statement is also disapproved of, so one is encouraged to code IF, or CASE, etc. and enjoy the repetition.

Thus, a subroutine (or a function) may exit via a RETURN statement, rather than by completing its logic and "falling out" of the end of its definition. If the subprogram is large, these escape holes may be missed by the (human) reader!

Persons writing in assembler have further opportunities, for example providing an integer function such as IOR(A,B) that performs an or on integers A and B. Instead of doing so, the function overwrites its invocation by placing in-line code that performs A or B, then returns not to its return address but to where it was invoked from so as to compute the result.

Away, and maybe, back

Similarly to escaping from a subroutine, within a DO-loop, a GO TO might jump out of the loop(s) - perhaps for good reason. More interesting is the possibility of jumping into a DO-loop's scope, possibly after jumping out - who knows what its index variable might have been changed to. This is considered poor form by others not writing such code and some compilers will reject any attempts. With the F77 introduction of IF ... THEN ... ELSE ... END IF constructions, jumping out of a block is still acceptable but jumping in is frowned on (even if only from the THEN clause to some part of its ELSE clause) and may be prevented.

F90 offers a more decorous means for exiting DO-loops, including the additional DO WHILE loop, via the statements CYCLE and EXIT - the text "GO TO" does not appear as such, but the effect is the same. The CYCLE option means abandoning further statements within the block to test afresh the iteration condition, while EXIT means ending the iteration as if it had completed. Further syntax allows some compiler checking, as follows:

      XX:DO WHILE(condition)
           statements...
        NN:DO I = 1,N        
             statements...
             IF (...) EXIT XX
             IF (...) CYCLE NN
             statements...
           END DO NN
         END DO XX

A DO-loop can be given a label such as XX (which is not in the numeric-only label area of fixed source format Fortran, and the syntax highlghter has missed yet another trick of Fortran syntax) and its corresponding END DO can be given a label also: the compiler checks that they match and some programmer errors might thereby be caught. With such labels in use, the CYCLE and EXIT statements can name the loop they are intended for, so that CYCLE NN steps to the next iteration for I (as if it were a GO TO the END DO having its label as a suffix) while the EXIT XX exits both the numeric DO-LOOP and the DO-WHILE loop - without such labels only the innermost loop is affected and one can lose track. These labels must not be the name of any other entity in the source, and specifically not the name of the variable of the DO-LOOP concerned. Thus, if there are many DO I = 1,N loops, each must have its own label. There is unfortunately no equivalent to NEXT I as in BASIC instead of END DOso as to be clear just which DO-LOOP is being ended and for which index variable.

Not returning at all

In for example Fortran IV, as on the IBM1130, a CALL EXIT stopped the run, which is to say, it "exited" to the operating system. As distinct from STOP which stopped the flow by stopping the cpu. Another no-return was provided by the likes of CALL LINK(PHASE2) where PHASE2 was not a text string in quotes. This caused the flow of execution to abandon the current programme and the operating system would load and run a programme called PHASE2. Code was loaded from low memory upwards, while storage in COMMON was assigned from high memory downwards and so long as desired data were not damaged by the new load, its processing would continue. Thus, if some data required a great deal of complex analysis and there was insufficient memory available to hold all the data plus all the code, it might be possible to split the processing into PHASE1 and PHASE2, etc.

Interruptions to the flow

More potent than RETURN is STOP, which ends the flow of execution there and then - without the need to signal some sort of "disaster" status so that each level of a nest of routines would return to its caller. Early Fortran also allowed STOP n where n was a number such as 303 and this value might be displayed on the computer's console display register in bright lights, or be printed in the job log, or on the standard output device. A later extension was STOP "message", but alas the message is only a fixed text, one can't devise a custom report such as "307 values! Limit is 300" as via STOP N," values! Limit is ",NMAX

Instead of STOP, there is PAUSE with the same syntax. The flow of execution would pause (that is, the entire computer would come to a stop in the days when one job only would run at a time), to be resumed with the next statement on the pressing of a button on the computer console for instance after the message "Attach output tape", or, ... the operator could via controls on the console inspect memory (on the decimal IBM1620, even floating-point numbers were easily parsed), modify memory, and cause execution to resume at some other (any other) chosen address...

Flowcharts?

A classic aid to design and analysis is a flowchart diagram, and there exist systems which will read the source code of a programme and draw its flowchart (on a graph plotter, say) with the various pieces of code appearing in blocks linked by lines showing the flow. Considering all the above (and not forgetting the arithmetic-IF and IF ... THEN ... ELSE ... ENDIF statements, DO-loops, DO WHILE loops and the SELECT and WHERE ... ELSEWHERE statements), this is no simple challenge.

Reaction

There is a famous letter by Edsger Dijkstra, titled Go To Statement Considered Harmful, published in the March 1968 Communications of the ACM.

Response

A thorough analysis of the problem appears in Structured Programming with go to Statements by Donald E. Knuth, December 1974. There's even mention of decision tables.


FreeBASIC

FreeBASIC has GOSUB and GOTO but they are obsolete.

Still, they are available when using the -lang qb dialect. This dialect provides the best support for the older QuickBASIC code.

'$lang: "qb"

Gosub subrutina

bucle:
Print "Bucle infinito"
Goto bucle
End

subrutina:
Print "En subrutina"
Sleep 100
Return
Sleep


Gambas

Click this link to run this code

Public Sub Main()
Dim siCount As Short

LOOPIT:

Print siCount;;
Inc siCount
If siCount > 100 Then Quit
Goto LoopIt

End

Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Go

Not covered here::

  • Structures involving for, if, switch, continue, break, fallthrough, or panic. As mentioned in the task description, these structures are covered in other tasks.
  • Short-circuit operators. These can be considered flow-control structures, but are also covered in other tasks.
  • Flow-control functions in the standard library. Many of these are important, but covering them seems beyond the scope of the task.

Goto

Go has goto and labels. The following is an infinite loop:

func main() {
inf:
    goto inf
}

Gotos can jump forward or backward within a function but they have some restrictions. They cannot jump into any block from outside the block, and they cannot cause any variable to come into scope.

Function call

Function call works as it does in most languages, transferring execution to to the called function, and returning execution to the following statement upon return from the called function.

The return statement returns from a function. Any function can use a return statement. Functions with return values can only return with a return statement. Functions without return values can return by “falling off” the end of the function.

The defer statement sets a function or method to be executed upon return from the enclosing function. This is useful when a function has multiple returns. The classic example is closing a file:

import "os"

func processFile() {
    f, err := os.Open("file")
    if err != nil {
        // (probably do something with the error)
        return // no need to close file, it didn't open
    }
    defer f.Close() // file is open.  no matter what, close it on return
    var lucky bool
    // some processing
    if (lucky) {
        // f.Close() will get called here
        return
    }
    // more processing
    // f.Close() will get called here too
}

Goroutines

Goroutines are Go’s take on lightweight threads. A goroutine is started with a go statement, which looks like “go” preceding a function call. When the go statement executes, a new goroutine is created, execution in the new goroutine starts with a call to the function named in the go statement, and execution in the calling goroutine continues concurrently. (The main thread of execution is a goroutine itself.)

The following program prints a mix of 1’s and 0’s.

package main

import "fmt"

func printOnes() {
    for {
        fmt.Println("1")
    }
}

func main() {
    go printOnes()
    for {
        fmt.Println("0")
    }
}

A goroutine terminates upon return from the function called in the go statement. Unlike with a regular function call however, it cannot return a value--the calling goroutine has long continued and there is nothing waiting for a return value.

Goroutines may not be able to communicate by returning values, but they have other ways. Principal is passing data through channels. Channel operations affect execution when they yield the processor, allowing other goroutines to run, but this does not normally alter flow of execution. The one exception is when channel operations are used in a select statement. A simple use,

func answer(phone1, phone2 chan int) {
    select {
    case <-phone1:
        // talk on phone one
    case <-phone2:
        // talk on phone two
    }
}

Syntax is strongly reminiscent of the switch statement, but rules for flow control are very different. Select will block if no channel operation is possible. If one is possible, it will execute that case. If multiple operations are possible, it will pick one at random.

Process initialization

A complete program must have exactly one function named main, which is called on program start up. In addition, a program can have any number of functions named init which are called before main. Package variables are initialized before init functions or main are called.

GW-BASIC

10 LET a=1
20 IF a=2 THEN PRINT "This is a conditional statement"
30 IF a=1 THEN GOTO 50: REM a conditional jump
40 PRINT "This statement will be skipped"
50 PRINT ("Hello" AND (1=2)): REM This does not print
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump

Haskell

In the context of normal, functional-style code, there are no flow-control statements, because explicit flow control is imperative. A monad may offer flow control; what kinds are available depends on the monad. For example, the ExitT monad transformer lets you use the exitWith function to jump out a block of statements at will.

import Control.Monad
import Control.Monad.Trans
import Control.Monad.Exit

main = do
    runExitTMaybe $ do
        forM_ [1..5] $ \x -> do
            forM_ [1..5] $ \y -> do
                lift $ print (x, y)
                when (x == 3 && y == 2) $
                    exitWith ()
    putStrLn "Done."

HicEst

More on HicEst's ALARM function

1 GOTO 2 ! branch to label

2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3

3 ALARM(delay, n) ! n=2...9 simulate F2 to F9 keys: call asynchronously "Alarm"-SUBROUTINES F2...F9 with a delay

4 ALARM(  1  ) ! lets HicEst wait at this statement for any keyboard or mouse event

5 SYSTEM(WAIT=1000) ! msec

6 XEQ('CALL my_subroutine', *7) ! executes command string, on error branch to label 7

7 y = EXP(1E100, *8) ! on error branch to label 8

8 y = LOG( 0 , *9)   ! on error branch to label 9

9 ALARM( 999 ) ! quit HicEst immediately

Icon and Unicon

Prelude about Goal-Directed Evaluation and Generators

Two of the key features of Icon and Unicon that affect program flow are Goal Directed Evaluation and Generators and Expression Failure. Goal Direction uses Generators to produce multiple results as needed and Expression Success and Failure forces the selection of logic pathways within programs.

goto
Does not exist in the Icon or Unicon language.

next
Restarts the enclosing loop. The conditional on the loop is evaluated as normal.

break expr
Default value of expr is the null value &null. This operator breaks out of the enclosing loop, yielding the expression as the result of the loop. Normally loops yield a failure ie no result, so you can write code like this:

    if x := every i := 1 to *container do {     # * is the 'length' operator
        if container[i] ~== y then
            write("item ", i, " is not interesting")
        else
            break a
    } then
        write("found item ", x)
    else
        write("did not find an item")

The expression given to break can be another break, which effectively lets you break out of two levels of loop. Finally, the expression given to break can be the next command; for example

    break break next

breaks out of two levels of loop and re-enters the top of the third-level enclosing loop.

return expr
Default value of expr is &null. Apart from the usual meaning of return, if the expr value fails, then the procedure actually fails too, ie does not yield a value. See description of fail keyword. If the expr is capable of yielding more than one result, only the first result is asked for and used.

fail
Causes the the enclosing procedure to terminate without returning value. This is different from returning void or a null value that many other languages do when the code does not return an actual value. For example, in

    x := ftn()

The value of x will not be replaced if ftn() issues the fail command. If ftn fails, then Goal-Directed Evaluation will also fail the assignment, therefore x is not assigned a new value. If the flow of control through a procedure falls off the end, the procedure implicitly fails.

suspend expr
Default value of expr is &null. Any procedure containing the suspend command will yield a value to the calling code. However the procedure remains in a state of suspended animation ready to be reactivated if the calling code demands another result due to Goal Directed Evaluation. Note that this capability is built directly into the runtime rather than being an artifically constructed behaviour provided by Python or C#'s use of the 'yield' keyword. Every and all expressions may suspend or be involved in a suspending expression without any effort. Behaviourally much closer to Prolog which also supports backtracking as a core part of the language. If the expr is capable of yielding more than one result, then supend (if driven) will progressively yield all of those values.

A procedure can contain several uses of suspend and it's quite reasonable for the procedure to execute many of them in any chosen order.

stop(expr)
Terminate program with prejudice.

error trapping
The keyword &error is normally zero, but if set to a positive value, this sets the number of fatal errors that are tolerated and converted to expression failure; the value of &error is decremented if this happens. Therefore the now-common TRY-CATCH behaviour can be written as:

    &error := 1
    mayErrorOut()
    if &error == 1 then
        &error := 0     # clear the trap
    else {
        # deal with the fault
        handleError(&errornumber, &errortext, &errorvalue)   # keyword values containing facts about the failure
    }

Various idiomatic simplifications can be applied depending on your needs.

error throwing
Errors can be thrown using the function

    runerr(errnumber, errorvalue)    # choose an error number and supply the offending value

IDL

goto

test:
..some code here
goto, test

(This is almost never used)

on_error

on_error, test

(This resumes at the label test if an error is encountered)

on_ioerror

on_ioerror, test

(Same as on_error, but for EOFs and read-errors and such)

break

break

immediately terminates the innermost current loop (or if or case etc)

continue

continue

immediately starts the next iteration of the current innermost loop

J

Control structures should usually [but not always] be avoided in J. J's primitives already provide iteration and selection.

For example, here's an example of a program which loops over a sequence of integers, multiplying them by two (j's default prompt is 3 spaces, which makes line-at-a-time copy-and-paste simple, and the result here is displayed on the following line):

   2 * 1 2 3
2 4 6

That said, J's control structures are documented at http://www.jsoftware.com/help/dictionary/ctrl.htm So, if you want to perform this same operation using a while loop, or a goto, you can do so. It's just... often not a good idea (but sometimes they are indispensable).

Java

"goto" is a reserved keyword in Java; but you cannot use it. There are currently no goto statements.

Java does provide two other statements that provide flow control: break and continue.

break

The break statement can be used to terminate a case clause in a switch statement and to terminate a for, while or do-while loop. In loops, a break can be labeled or unlabeled.

switch (xx) {
  case 1:
  case 2:
    /* 1 & 2 both come here... */
    ...
    break;
  case 4:
    /* 4 comes here... */
    ...
    break;
  case 5:
    /* 5 comes here... */
    ...
    break;
  default:
    /* everything else */
    break;
}

for (int i = 0; i < 10; ++i) {
  ...
  if (some_condition) { break; }
  ...
}

_Time_: do {
  for (int i = 0; i < 10; ++i) {
    ...
    if (some_condition) { break _Time_; /* terminate the do-while loop */}
    ...
    }
  ...
} while (thisCondition);

continue

The continue statement skips the current iteration of a for, while, or do-while loop. As with break the continue statement can be labeled or unlabeled to allow iterating a loop level other than the current one in nested loops.

while (condition) {
  ...
  if (someCondition) { continue; /* skip to beginning of this loop */ }
  ...
}

top: for (int 1 = 0; i < 10; ++i) {
  ...
  middle: for (int j = 0; j < 10; ++j) {
    ...
    bottom: for (int k = 0; k < 10; ++k) {
    ...
    if (top_condition) { continue top; /* restart outer loop */ }
    ...
    if (middle_condition) { continue middle; /* restart middle loop */ }
    ...
    if (bottom_condition) { continue bottom; /* restart bottom loop */ }
    ...
    if (bottom_condition) { continue; /* this will also restart bottom loop */ }
    ...
    }
    ... 
  }
  ....
}

JavaScript

  • return from a function ([1])
  • yield from a generator function ([2])
  • yield* from a generator function ([3])
  • await from an async function ([4])
  • loop control with break [label] ([5]) and continue [label] ([6])
  • exceptions with throw ([7]) and try ... catch ... finally ... ([8])

jq

jq 1.5 introduced `break` and `label` keywords for defining backtracking points. These are used to terminate a generator before completion. Here is a contrived example that illustrates the main points:

$ jq -n '1, (2 | label $foo | debug | 3 | break $foo | debug), 4'
1
["DEBUG:",2]
4

Here is an example from the standard library:

# Emit at most one item from the stream generated by g:
def first(g): label $out | g | ., break $out;

Julia

Julia provides the @goto and @label macros for goto within functions. In addition, the "break" keyword is used for jumping out of a single loop, throw() of an exception can be used to jump out of a try() statement's code, and the assert() and exit() functions can be used to terminate a program.

function example()
    println("Hello ")
    @goto world
    println("Never printed")
    @label world
    println("world")
end

Kotlin

Kotlin does not have a 'goto' statement but does have 'break' and 'continue' statements to jump out of or continue with the next iteration of a loop. The 'labelled' versions of these statements have already been described at Jump_anywhere#Kotlin and so only the basic versions are described in this task which jump out or continue with the nearest enclosing loop.

Kotlin also has a 'throw' statement which throws (or rethrows) an exception.

Here are some examples:

// version 1.0.6

fun main(args: Array<String>) {
    for (i in 0 .. 2) {
        for (j in 0 .. 2) {
            if (i + j == 2) continue
            if (i + j == 3) break
            println(i + j)
        }
    }
    println()
    if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
    println("Goodbye!")  // won't be executed
}
Output:
c:\kotlin-compiler-1.0.6>java -jar control_flow.jar arg1 arg2
0
1
1

Exception in thread "main" java.lang.IllegalArgumentException: No command line arguments should be supplied
        at Control_throwKt.main(control_throw.kt:12)

Lua

Lua has the break-command to exit loops.

i = 0
while true do
    i = i + 1
    if i > 10 then break end
end

Tail calls as GOTOs

The following code - though obviously a useless infinite loop - will not cause a stack overflow:

function func1 ()
  return func2()
end

function func2 ()
  return func1()
end

func1()

This is because Lua supports proper tail recursion. This means that because something being returned is necessarily the last action in a function, the interpreter treats a function call in this 'tail' position much like a GOTO in other languages and does not create a new stack level.

M2000 Interpreter

M2000 has labels, Goto, Gosub, On Goto, On Gosub, and can use numeric labels immediate at Then and Else clause. Goto can be used inside a block, or structure which may have hidden block. We can't use Goto to jump to outer module (calling module). Also we can't start a module from a label.

Gosub level controlled by Recursion.Limit (which is 10000 by default but we can change it to anything, like 1000000, using Recursion.limit 1000000), depends only from size of memory for 32bit applications (2Gbyte).

Every is a block structure for execution code synchronized by timer. If code exit execution time of block's constant time, executed later at same phase. There are three more statements for tasks, AFTER, THREAD and MAIN.TASK for executing code based on time in sequential of concurrent fashion, not shown here.

We can use Error "name of error" to produce error and we can catch it through a Try block.


Use of Labels

Module Inner {
	long x=random(1, 2)
	on x goto 90, 100
090	print "can print here if is "+x  // if x=1
100	Print "ok"
	gosub 500
alfa:  // no statement here only comments because : is also statement separator
	print "ok too"
	integer c
	Every 100 { // every 100 miliseconds this block executed
		c++
		gosub printc
		if c>9 then 200
	}
	print "no print here"
200	Gosub exitUsingGoto
	Every 100 { // every 100 miliseconds this block executed
		c++
		gosub printc
		if c>19 then exit
	}
	gosub 500
	try ok {
		on x gosub 400, 1234
	}
	if ok else print error$ // sub not found (if x=2)
	goto 1234  ' not exist so this is an exit from module
400	print "can print here if is "+x  // if x=1
	end
printc:
		Print c
		return
500	Print "exit from block using exit" : return
exitUsingGoto:
		Print "exit from block using goto"
		return
}
Inner

Use of Call Back function

M2000 has no yield statement/function. We can use a call back function to get results, before a module exit. The call back function act as code in the calling module (has same scope), but has a difference: we can't use goto/gosub out of it

module outer {
	static m as long=100  // if m not exist created
	module count (&a(), b) {
		long c=1
		do
			if b(c) then exit
			call a(c)
			c++
		always
	}
	
	long z, i=100
	// function k used as call back function, through lazy$()
	function k {
		read new i
		print i   // print 1 and 2
		z+=i
		m++
	}
	
	count lazy$(&k()), (lambda (i)->i>=3)
	print z=3, i=100, m
}
clear  // clear variables (and static variables) from this point
outer // m is 102
outer // m is 104
outer // m is 106

Using Break/Continue in Select Case

Normally the Break statement break module (exit from module) or a Try { } block. Normally Continue is like exit in ordinary blocks or a new iteration for loop structures. For a Select case, a Break make the execution of other blocks from other cases to executed until "case else" or a continue statement. Both ends goes to end select. So break works in reverse of c's break. Without block { } in cases, Break and Continue works for the outer block (like normal break and continue). We can use Goto in cases, to exit select/end select structure, using or not using block in cases. Gosub can be used as usual everywhere.

Module checkSelect {
	long m, i, k
	for k=1 to 10
	m=10
	i=random(5, 10)
	select case i
	case <6
		print "less than 6"
	case 6
	{
		m++: break   // break case block, and continue to next block
	}
	case 7
	{
		m++: break 
	}
	case 8
	{
		m++: continue // exit after end select
	}
	case 9
		print "is 9"
	case else
		print "more than 9"
	end select
	print m, i
	next
}
checkSelect

Mathematica / Wolfram Language

Relevant functions are:

TimeConstrained[expr,t] evaluates expr, stopping after t seconds.

MemoryConstrained[expr,b] evaluates expr, stopping if more than b bytes of memory are requested.

Goto[tag] scans for Label[tag], and transfers control to that point.

CreateScheduledTask[expr,t] creates a task that will repeatedly evaluate expr every t second.

Interrupt[] interrupt a computation

Abort[] abort a computation

Quit[] immediately stops all execution and returns to the top level read-eval-print loop

Catch[] prepares for receiving a Throw[] while running a given list of executable expressions

Throw[] causes a non-local jump to a specified Catch[]

MATLAB / Octave

 
try 
   % do some stuff
catch
   % in case of error, continue here
end

Maxima

/* goto */
block(..., label, ..., go(label), ...);

/* throw, which is like trapping errors, and can do non-local jumps to return a value */
catch(..., throw(value), ...);

/* error trapping */
errcatch(..., error("Bad luck!"), ...);

MUMPS

GOTO / G

The GOTO command jumps to a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name.

GOTO LABEL^ROUTINE

. This does not affect the subroutine stack, only the program pointer.

GOTO THERE

HALT / H

Halt and Hang have the same abbreviation, i.e. "H" but (as a mnemonic) Halt takes no arguments. Halt stops the current process, and clears all Locks and devices in Use. On the Cache variant of MUMPS, there is a $HALT special variable that can be set, the value of the $HALT special variable is a routine that is called before cleaning up (in effect, a specialized final error trap).

 Read "Do you really wish to halt (Y/N)?",Q#1
 IF Q="Y"!Q="y" HALT

JOB / J

The JOB command starts another MUMPS job starting at a label. If the label is not in the current routine, it is necessary to include the circumflex and routine name.

JOB LABEL^ROUTINE

.

JOB THERE

This does not affect the subroutine stack, nor the program pointer in the current job. Since MUMPS is a multi-processing (rather than multi-threading) language, the new job is independent of the current job.

 JOB LABEL^ROUTINE


QUIT / Q

Exits a loop, or routine. It decreases the stack level. It can return a value to a calling routine if there is a value after it.

Quit is one of the commands that requires two spaces after it if it is followed in a line by more commands.

FOR I=1:1:1 QUIT:NoLoop  DO YesLoop
QUIT Returnvalue

XECUTE / X

eXecute acts as if it were a one line Do command. Its argument must be a string of valid MUMPS code, and it performs that code in a new stack level. There is an implied Quit at the end of each eXecute's argument string.

 SET A="SET %=$INCREMENT(I)"
 SET I=0
 XECUTE A
 WRITE I

The above block will output "1".

Nemerle

Flow control statements made available in the Nemerle.Imperative namespace: break, continue, return (to return from somewhere other than the last expression in a function).

Exceptions can also be used to transfer control from a try block to a catch block.

NetRexx

NetRexx doesn't have a GOTO instruction and unlike Rexx the SIGNAL instruction is only used to throw exceptions.

Like Rexx however, NetRexx provides the LEAVE and ITERATE instructions.

LEAVE

The LEAVE instruction causes immediate exit from one or more DO, SELECT or LOOP constructs.

loop xx = 1 to 10
  if xx = 1 then leave -- loop terminated by leave
  say 'unreachable'
  end

A name parameter can be provided to direct LEAVE to a specific end of block (as defined by a LABEL option or in the case of a controlled LOOP the control variable of the loop.

loop xx = 1 to 10 -- xx is the control variable
  ...
  loop yy = 1 to 10 -- yy is the control variable
    ...
    if yy = 3 then leave xx -- xx loop terminated by leave
    if yy = 4 then leave yy -- yy loop terminated by leave
    ...
    end
    ...
  end xx

loop label xlabel xx = 1 to 10 -- xx is still the control variable but LABEL takes precidence
  ...
  loop yy = 1 to 10 -- yy is the control variable
    ...
    if yy = 3 then leave xlabel -- xx loop terminated by leave
    ...
    end yy
    ...
  end xlabel

do label FINIS
  say 'in do block'
  if (1 == 1) then leave FINIS
  say 'unreachable'
  signal Exception("Will never happen")
catch ex = Exception
  ex.printStackTrace()
finally
  say 'out of do block'
end FINIS

loop vv over ['A', 'B']
  select label selecting case vv
    when 'A' then do; say 'A selected'; say '...'; end
    when 'B' then do;
      say 'B selected';
      if (1 == 1) then leave selecting;
      say '...';
      end
    otherwise do; say 'nl selection'; say '...'; end 
    end selecting
  end vv

ITERATE

The ITERATE instruction alters flow of control within a LOOP construct. On encountering an ITERATE instruction, execution of the loop body is terminated and control is passed directly back to the top of the loop just as though the last clause in the body of the loop had been executed.

As with LEAVE an optional name parameter can be supplied to direct the instruction to a loop level outside the current level.

loop fff = 0 to 9
  ...
  loop xx = 1 to 3
    ...
    if fff > 2 then iterate fff
    ...
    end
  ...
  end fff

Nim

Labeled Break & Continue

Break and continue can be used with block labels to jump out of multiple loops:

block outer:
  for i in 0..1000:
    for j in 0..1000:
      if i + j == 3:
        break outer

Try-Except-Finally

var f = open "input.txt"
try:
  var s = readLine f
except IOError:
  echo "An error occurred!"
finally:
  close f

OCaml

An OCaml user can simulate flow control using exceptions:

exception Found of int

let () =
  (* search the first number in a list greater than 50 *)
  try
    let nums = [36; 23; 44; 51; 28; 63; 17] in
    List.iter (fun v -> if v > 50 then raise(Found v)) nums;
    print_endline "nothing found"
  with Found res ->
    Printf.printf "found %d\n" res

Oforth

Oforth does not have goto statement.

break allows to break the current loop :

break

continue allows to immediately start a new iteration :

continue

perform is a method that transfer execution to the runnable on top of the stack, then returns :

perform

Oz

Exception handling is documented in other tasks: Exceptions#Oz, Exceptions Through Nested Calls#Oz.

The case statement can be used for Pattern Matching, but also like a switch statement in C:

case {OS.rand} mod 3
of 0 then {Foo}
[] 1 then {Bar}
[] 2 then {Buzz}
end

The Lisp-influenced for-loop is very powerful and convenient to use.

As a constraint programming language, Oz has a number of flow control structures which target logic programming. They are typically used to implement new constraint search engines. However, it is also possible to use them for general logic programming.

  • or: speculatively executes a number of alternative conditions and blocks until at most one alternative remains valid. Then either fails or commits to the remaining alternative if there is one.
  • cond: evaluates a number of conditions in parallel (or in undefined order) and commits to the first alternative that succeeds.
  • dis: depreciated
  • choice: creates a non-deterministic choice point. In other words, the statement provisionally chooses an alternatives. If the choice turns out to be wrong or if additional solutions to a puzzle are searched, another alternative is chosen.

As an example for choice, a simple, but stupid way to solve the equation 2*X=18. We assume that the solution is somewhere in the interval 8-10, but we do not quite know what exactly it is.

declare
  proc {Stupid X}
     choice
        X = 8
        {System.showInfo "choosing 8"}
     [] X = 9
        {System.showInfo "choosing 9"}
     [] X = 10
        {System.showInfo "choosing 10"}
     end
  
     2 * X = 18
  end
in  
  {Show {SearchOne Stupid}}
Output:
choosing 8
choosing 9
[9]

PARI/GP

Flow control structures include function calling and returning, error/trap, next/break, alarm, and the various loops.

Pascal

goto

label
  jumpto;
begin
  ... 
jumpto:
  some statement;
  ...
  goto jumpto;
  ...
end;

exception

try
  Z := DoDiv (X,Y);
except
  on EDivException do Z := 0;
end;

Halt

Halt stops program execution and returns control to the calling program. The optional argument Errnum specifies an exit value. If omitted, zero is returned.

procedure halt(errnum: Byte);

Exit

Exit exits the current subroutine, and returns control to the calling routine. If invoked in the main program routine, exit stops the program. The optional argument X allows to specify a return value, in the case Exit is invoked in a function. The function result will then be equal to X.

procedure exit(const X: TAnyType)

Calls of functions/procedures as well as breaks and continues in loops are described in the corresponding tasks.

Perl

Works with: Perl version 5.x

goto

Goto is typically looked down upon by most Perl programmers

FORK:
# some code
goto FORK;

Phix

Library: Phix/basics

goto

In 0.8.4+ Phix finally has a goto statement:

without js -- (no goto in JavaScript)
procedure p()
    goto :but_print
    puts(1,"This will not be printed...\n")
::but_print
    puts(1,"...but this will\n")
end procedure
p()

Imposing a self-policed rule that all jumps must be forward (or equivalently all backward, but never mixed) is recommended.

Phix imposes the following limitations on the use of goto statements:
A goto statement must be in the same function as the label it is referring.
The goto statement is not supported in top level code, outside of a routine definition.
There are no computed, assigned, or multiple target forms of the goto statement.
Goto may not be used and labels may not be defined anywhere inside a try/catch statement.
Jumping over variable initialisation will, naturally, leave the variable unassigned.
A goto can optionally refer to label or :label - they mean the same thing.
(Technically the colon-less variant is shorthand for the formal with-colon label reference.)
A label, which adheres to the usual identifier rules, is defined by preceding it with a double colon.

Note that a goto statement, or inline assembly (a goto statement is implemented using fragments of auto-generated inline assembly) will cause the compiler to abandon certain optimisation efforts, in particular type inferencing and constant propagation, which can result in a larger and slower program.

Previous versions had no hll goto statement, however the following work around was (and still is) available:

without js
#ilASM{ jmp :label }
...
#ilASM{ ::label }

In top level code, label scope is restricted to a single ilASM construct, but within a routine, the scope is across all the ilasm in that routine.

There is quite deliberately no support for jumping from the middle of one routine into another: without a frame, then quite simply parameters and local variables have not been allocated and cannot be used/referenced.

It is also possible to declare global labels, which are superficially similar:

without js
#ilASM{ call :%label }
...
#ilASM{ jmp :skip
       :%label
        ret
       ::skip }

Global labels cannot be declared inside a routine, and as shown (almost always) require a skip construct. It is up to the programmer to ensure global labels are unique across the entire application. Note that global labels are both declared and referenced with ":%", whereas local labels are declared with "::" but referenced with ":".

<it was claimed> Making "goto" somewhat more difficult to type in this manner ensures that it is far less likely to be abused, and discourages newbie programmers from adopting it as a weapon of choice, as usually(/always) happens with a hll goto. </it was claimed>

continue

Personally I must agree with Douglas Crockford who says "I have never seen a piece of code that was not improved by refactoring it to remove the continue statement".
Causes the next interation of the immediately surrounding loop to begin immediately, with any condition evaluated normally. The following two loops behave identically:

with javascript_semantics
for i=1 to 100 do
    if a[i]=0 then continue end if
    ...
end for

for i=1 to 100 do
    if a[i]!=0 then
        ...
    end if
end for

exit

causes immediate termination of the immediately surrounding for or while loop, with control passing to the first statement after the loop, eg:

with javascript_semantics
for i=1 to 100 do
    if a[i]=x then
        location = i
        exit
    end if
end for

break

Terminate a switch statement. fallthrough is the opposite, overriding an implicit break between cases.
Note that JavaScript uses break for both switch and loop constructs, therefore pwa/p2js imposes additional rules to ensure compatibility, ie sufficiently nested/anything JavaScript can do is fine, but while desktop/Phix allows a loop to directly exit a switch and vice versa, the transpiler terminates in error when it detects any such attempts.

return

Exits the current routine. Needs a value to return if used inside a function or type.

abort, crash, throw

Terminate the entire application immediately, unless caught by a containing try/catch statement.
Technically it is possible to use these to effect control flow, albeit in a grossly inefficient manner.

tasks and threads

Phix supports both multitasking and multithreading. In multitasking, at most one task is currently running, so no locking is required, and the application explicitly invokes task_yield to indicate when it is safe to switch between tasks. Multithreading is potentially much trickier, everything that could be accessed concurrently must be locked - however when one thread is stalled, perhaps waiting for a network response, the other threads are unaffected.

PHP

Works with: PHP version 5.3

goto

Introduced in PHP 5.3, PHP now has a goto flow-control structure, even though most PHP programmers see it as a bad habbit (may cause spaghetti-code).

<?php
goto a;
echo 'Foo';
 
a:
echo 'Bar';
?>
Output:
Bar

PicoLisp

As this task asks for the documentation of common flow control structures, we refer here to the online documentation for more complete descriptions and examples.

Relevant functions are:

fork

fork creates a child process

task

task installs a background task consisting of an environment and a list of executable expressions

alarm

alarm schedules a timer, which runs a given list of executable expressions when it expires

abort

abort runs a given list of executable expressions, and aborts processing it if it takes longer than a given time

quit

quit immediately stops all execution and returns to the top level read-eval-print loop, optionally signaling an error

wait

wait delays current processing (optionally to a maximal time) until an optionally given condition evaluates to non-NIL

sync

sync synchronizes with other processes of the same family

protect

protect delays the processing of signals while a given list of executable expressions is executed

catch

catch prepares for receiving a 'throw' while running a given list of executable expressions

throw

throw causes a non-local jump to a specified 'catch' environment

bye

bye exits the interpreter

finally

finally specifies a list of executable expressions, to be run when current processing is done, even if a 'throw' or 'bye' was executed, or an error occurred.

PL/I

LEAVE
   The LEAVE statement terminates execution of a loop.
   Execution resumes at the next statement after the loop.
ITERATE
   The ITERATE statement causes the next iteration of the loop to
   commence.  Any statements between ITERATE and the end of the loop
   are not executed.
STOP
   Terminates execution of either a task or the entire program.
SIGNAL FINISH
   Terminates execution of a program in a nice way.
SIGNAL statement
   SIGNAL <condition> raises the named condition.  The condition may
   be one of the hardware or software conditions such as OVERFLOW,
   UNDERFLOW, ZERODIVIDE, SUBSCRIPTRANGE, STRINGRANGE, etc, or a
   user-defined condition.
CALL
   The CALL statement causes control to transfer to the named 
   subroutine.
SELECT
   The SELECT statement permits the execution of just one of a
   list of statements (or groups of statements).
   It is sort of like a computed GOTO.
GO TO
   The GO TO statement causes control to be transferred to the named
   statement.
   It can also be used to transfer control to any one of an array of
   labelled statements. (This form is superseded by SELECT, above.)
   [GO TO  can also be spelled as  GOTO].

Pop11

quitloop

quitloop with argument exits from nested loops:

while condition1 do
   while condition2 do
      if condition3 then
         quitloop(2);
      endif;
   endwhile;
endwhile;

above quitloop(2) exits from both loops.

goto

goto l transfers control to the label l. goto may be used to exit from nested loops:

while condition1 do
   while condition2 do
      if condition3 then
         goto l;
      endif;
   endwhile;
endwhile;
l:;

Another use is to implement finite state machines:

state1:
   DO_SOMETHING();
   if condition1 then 
      goto state1;
   elseif condition2 then
      goto state2;
   ....
   else
      goto stateN;
   endif;
state2:
   ....
...
...
stateN:
   ....

Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure calls:

define outer();
   define inner(n);
      if n = 0 then
         goto final;
      endif;
      inner(n - 1);
   enddefine;
   inner(5);
   final:;
enddefine;

This is useful to exit early from successful recursive search, and for exception handling.

go_on

go_on is a multiway jump

go_on expression to lab1, lab2, ..., labN else elselab ;

If expression has value K the above will jump to label labK, if expression is not an integer, or if it outside 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 chosen by the user.

return

return ends execution of current function. In simplest form it is just:

return;

but it is also possible to specify one or more return values:

return(val1, val2, val3);

chain

chain has effect of "tail call" but is not necessarily in tail position. More precisely inside proc1.

chain proc2(x1, x2, x3);

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 explicitly use chain.

PureBasic

Goto

Transfers control to the label referenced. It is not a safe way to exit loops.

If OpenConsole()
  top:
  i = i + 1
  PrintN("Hello world.")
  If i < 10
    Goto top
  EndIf 
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf

Gosub & Return

Gosub stands for 'Go to sub routine'. A label must be specified after Gosub where the program execution continues and will do so until encountering a Return. When a return is reached, the program execution is then transferred immediately below the Gosub. Gosub is useful when building fast structured code with very low overhead.

X=1:  Y=2
Gosub Calc
;X will now equal 7
End

Calc:
  X+3*Y
  Return ; Returns to the point in the code where the Gosub jumped from

FakeReturn

If the command Goto is used within the body of a sub routine, FakeReturn must be used to correct the stack or the program will crash.

Gosub MySub

Lable2:
; The program will jump here, then 'end'
End

MySub:
If #PI>3
  FakeReturn  ; This will simulate the function of a normal "Return".
  Goto Lable2
EndIf 
Return

OnErrorGoto

This will transferee the program execution to the defined label if an error accrue.

OnErrorGoto(?MyExitHandler)

X=1: Y=0
z= X/Y
; = a illegal division with zero
Debug "This line should never be reached"
End

MyExitHandler:
  MessageRequester("Error", ErrorMessage())
  End

OnErrorCall

Similar to OnErrorGoto() but procedural instead.

Procedure MyErrorHandler()
  ;All open files etc can be closed here
  MessageRequester("Error", ErrorMessage())
  End
EndProcedure

OnErrorCall(MyErrorHandler())
X=1: Y=0
Z= X/Y
;This line should never be reached

Python

Loops

Python supports break and continue to exit from a loop early or short circuit the rest of a loop's body and "continue" on to the next loop iteration.

# Search for an odd factor of a using brute force:
for i in range(n):
    if (n%2) == 0:
        continue
    if (n%i) == 0:
        result = i
        break
else:
    result = None
    print "No odd factors found"

In addition, as shown in the foregoing example, Python loops support an else: suite which can be used to handle cases when the loop was intended to search for something, where the code would break out of the loop upon finding its target. In that situation the else: suite can be used to handle the failure. (In most other languages one is forced to use a "sentinel value" or a special flag variable ... typically set to "False" before the loop and conditionally set to "True" within the loop to handle situations for which the Python else: on loops is intended).

Exceptions

A Python exception is simply any subclass of the built-in BaseException class, or any of its descendents. User defined exception classes are normally descendents of the Exception class (which is, itself, a subclass of BaseException). To "throw" any exception (user defined or otherwise) one uses the raise statement. To capture exceptions one must enclose the code in a try: ... except...: block. Any exception listed in an except block will catch all subclasses of that exception. For example ZeroDivisionError is derived from ArithmeticError. Thus an exception clause for ArithmeticError would catch a ZeroDivisionError (or any other ArithmeticError).

As a consequence of this one must arrange the order of exception clauses such that the more specific exceptions are listed (caught) before their more general base exceptions. Only the first matching exception clause will be executed. An except clause which lists no exceptions will catch all possible exceptions. (This is usually considered to be very poor programming practice because it can hide unintended coding errors).

An exception can be re-raised by simply calling the raise statement without any arguments (from within any exception handler). Thus a function can catch an exception, attempt to deal with it, then, if necessary, throw it it back to the next layer out in a given call stack. Uncaught exceptions will be handled by the interpreter by terminating the program and printing an error message and stack trace.

A custom Exception class is normally declared with the pass statement as no methods of the parent class are over-ridden, no additional functionality is defined and no attributes need be set. Example:

class MyException(Exception): pass

One normally would choose the most similar existing class. For example if MyException was going to be raised for some situation involving an invalid value it might be better to make it a subclass of ValueError; if it was somehow related to issues with inappropriate objects being passed around then one might make it a subclass of TypeError.

In large projects it's common to create an custom application base exception and to have all or most custom exceptions within that application or framework derive therefrom.

To create a "virtual base class" (one which is not intended to be directly instantiated, but exists solely to provide an inheritance to it's derived classes) one normally defines the requisite methods to raise "NotImplementedError" like so:

class MyVirtual(object):
    def __init__(self):
        raise NotImplementedError

It then becomes necessary for any descendants of this class to over-ride the __init__() method. Any attempt to instantiate a "MyVirtual" object directly will raise an exception.


Case 1 - Try, Except

try:
    temp = 0/0
# 'except' catches any errors that may have been raised between the code of 'try' and 'except'
except:   # Note: catch all handler ... NOT RECOMMENDED
    print "An error occurred."
# Output : "An error occurred"

Case 2 - Try, Except

try:
    temp = 0/0
# here, 'except' catches a specific type of error raised within the try block.
except ZeroDivisionError:
    print "You've divided by zero!"
# Output : "You've divided by zero!"

Case 3 - Try, Except, Finally

try:
    temp = 0/0
except:
    print "An error occurred."
# here, 'finally' executes when the try - except block ends, regardless of whether an error was raised or not    
# useful in areas such as closing opened file streams in the try block whether they were successfully opened or not
finally:
    print "End of 'try' block..."
# Output :
# An error occurred
# End of 'try' block...

Note: Prior to version 2.5 a try: statement could contain either series of except: clauses or a finally: clause but not both. It was thus necessary to nest the exception handling in an enclosing try:...finally: loop like so:

try:
    try:
        pass
    except (MyException1, MyOtherException):
        pass
    except SomeOtherException:
finally:
    do_some_cleanup() # run in any case, whether any exceptions were thrown or not

Case 4 - Try, Except, Else

try:
    temp = 1/1 # not a division by zero error
except ZeroDivisionError: # so... it is not caught
    print "You've divided by zero."
# here, 'else' executes when no exceptions are caught...
else:
    print "No apparent error occurred."
# Output :
# No apparent error occurred.

Case 5 - Try, Except, break, continue

i = 0
while 1: # infinite loop
    try:
       temp2 = 0/i # will raise a ZeroDivisionError first.
       temp = math.sqrt(i)
       
       break # 'break' will break out of the while loop
    except ValueError: #
        print "Imaginary Number! Breaking out of loop"
        break # 'break' out of while loop
    except ZeroDivisionError:
        print "You've divided by zero. Decrementing i and continuing..."
        i-=1 # we decrement i.
        # we 'continue', everything within the try - except block will be executed again, 
        # this time however, ZeroDivisionError would not be raised again.
        continue # Note that removing it, replacing it with 'pass' would perform the equivalent
                 # see below for a better example
# Output :
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop

Case 6 - Creating your own custom exceptions, raise

# Let's call our custom error "StupidError"; it inherits from the Exception class

class StupidError(Exception): pass
        
# Try it out.
try:
    raise StupidError("Segfault") # here, we manually 'raise' the error within the try block
except StupidError, details: # 'details' is the StupidError object we create in the try block.
    print 'Something stupid occurred:', details # so we access the value we had stored for it...
        

# Output :
# Something stupid occurred: Segfault

continue, else in "for" loop

    i = 101
    for i in range(4): # loop 4 times
        print "I will always be seen."
        if i % 2 == 0:
            continue # continue goes back to the loop beginning for a new iteration.
        print "I'll only be seen every other time."
    else:
        print "Loop done"
    
    # Output:
    # I will always be seen.
    # I will always be seen.
    # I'll only be seen every other time.
    # I will always be seen.
    # I will always be seen.
    # I'll only be seen every other time.
    # Loop done
        
if(__name__ == "__main__"):
    main()

The "with" statement

Works with: Python version 2.6

See [PEP 0343, The "with" statement]

class Quitting(Exception): pass
max = 10 
with open("some_file") as myfile:
    exit_counter = 0
    for line in myfile:
        exit_counter += 1
        if exit_counter > max:
            raise Quitting 
        print line,

The with statement allows classes to encapsulate "final" (clean-up) code which will automatically be executed regardless of exceptions that occur when working "with" these objects. Thus, for the foregoing example, the file will be closed regardless of whether it's more than 10 lines long. Many built-in and standard library classes have "context managers" which facilitate their use in with: code. In addition it's possible to define special __enter__() and __exit__() methods in one's own classes which will be implicitly called by the interpreter when an object is used within a with: statement.

Use cases for with: enabled objects include automated/guaranteed closing of files, release of threading lock objects, commit or rollback of database transactions, and save/restore of any desired state (such as terminal settings when using the curses module, the precision settings when using the Decimal module, or even saving and restoring sys.stdout for temporary redirection). It is a feature that seems to be unique to Python.

Yield expressions

Works with: Python version 2.5

See [PEP 0342, Coroutines via Enhanced Generators]

>>> value = 1
>>> echo = lambda: (yield value)
>>> for i in echo():
...   print i
...
1

Quackery

A Quackery program is a dynamic array (nest) of numbers (bigints) operators (opcodes or primitives) and nests (named or explicit). It is evaluated by a depth first traversal of the structure, placing numbers on a data stack, and keeping track of the evaluation with a return stack. Flow control is achieved with meta-control flow operators, which modify the return stack during evaluation. The naming convention for meta-control flow operators is to wrap them in reversed brackets. They are ]again[ ]done[ ]if[ ]iff[ ]else[ ]'[ ]do[ ]this[ and ]bailby[.

The first five, ]done[ ]again[ ]if[ ]iff[ ]else[, are used to create a mix and match set of control flow words.

[ ]again[ ] is again
[ ]done[ ]  is done
[ ]if[ ]    is if
[ ]iff[ ]   is iff
[ ]else[ ]  is else

again causes evaluation of the current nest to start again.

done causes evaluation of the current nest to end, and evaluation of the calling nest to continue.

if conditionally skips over the next item in the nest being evaluated. (dependant on the top of the data stack; it skips if the TOS is zero, and does not skip if it is a non-zero number. If it is not a number evaluation halts and a problem is reported.

iff is like if but conditionally skips over the next two items. It combines with else (below) to form an if...else... construct, and with other words to form more control flow structures (below).

else unconditionally skips over the next item in the nest being evaluated.

Also provided are until and while, and the programmer can add more as desired.

[ not if ]again[ ] is until
[ not if ]done[ ]  is while

As this is a mix and match word set, complex control-flow structures can be made, restricted only to single-point of entry, achieved by the intentional omission of a go-to operator. For example, this code fragment from the task Largest number divisible by its digits.

  [ 504 -
    dup digits
    dup 5 has iff
      drop again
    dup 0 has iff
      drop again
    repeats if again ]

' do thisenable first and higher order functions, and recursion. They are defined using meta control flow operators.

[ ]'[ ]    is '
[ ]do[ ]   is do
[ ]this[ ] is this

' unconditionally skips over the next item in the current nest, and places (a pointer to) it on the data stack.

do evaluates the item on the top of the data stack.

this places (a pointer to) the nest currently being evaluated on the data stack. so, for example, the phrase this do will cause the nest containing the phrase to be evaluated recursively. For convenience, the word recurse is provided which does the same thing.

[ ]this[ do ] is recurse

For more complex recursive situations the words this and do can be deployed at different levels of nesting, and additionally a forward referencing mechanism is provided. This example is from the task Mutual recursion.

                  forward is f ( n --> n )

  [ dup 0 = if done
    dup 1 - recurse f - ] is m ( n --> n )
   
  [ dup 0 = iff 1+ done
    dup 1 - recurse m - ]
                    resolves f ( n --> n )

]'[ and do are also used to create the iterative looping word times, which will repeat the next item in the nest a specified number of times. The index of the loop is available from the word i^, which counts up from zero with each iteration, and the word i, which counts down to zero. The index can be modified with the words step, which causes the index to be incremented by a specified number, refresh, which resets it to the originally specified number of iterations, and conclude, which will sets it to zero.

times is used in the definition of witheach, which iterates over a nest placing the next item in the nest on the data stack with each iteration, so I^ I step refresh conclude are available within witheach loops.

  ' [ 10 11 12 13 14 15 16 17 18 19 ]
  witheach
    [  dup 14 > iff
         [ drop conclude ] done
       echo
       say " is item number " i^ echo cr
       2 step ]
Output:
10 is item number 0
12 is item number 2
14 is item number 4

witheach can be used to define Higher-order functions.

]bail-by[ removes a specified number of returns from the return stack. This is a high risk activity, as the data stack and ancillary stacks used by times and others are not restored in the process, additionally many words add items to the return stack that need to be accounted for. Without proper precautions it is an effective way of causing unpredictable behaviour (usually crashing). It exists primarily for the backtracking provided by the words backup, bail, and bailed, which do take the proper precautions.

Racket

exit

Racket's exit quits the whole process, optionally returning an exit code. Note that there is an exit-handler that can be set to intercept such exit attempts.

goto

Racket doesn't have a goto, but like other implementations of Scheme, it adopts the mantra of "Lambda: the Ultimate GOTO" by having all tail calls optimized. This allows writing code that is no different from your average assembly code -- for example, here's a direct translation of Greatest_common_divisor#x86_Assembly into a Racket function:

#lang racket

;; some silly boilerplate to mimic the assembly code better
(define r0 0)
(define (cmp r1 r2) (set! r0 (sgn (- r1 r2))))
(define (je true-label false-label) (if (zero? r0) (true-label) (false-label)))
(define (goto label) (label))

(define (gcd %eax %ecx)
  (define %edx 0)
  (define (main) (goto loop))
  (define (loop) (cmp 0 %ecx)
                 (je end cont))
  (define (cont) (set!-values [%eax %edx] (quotient/remainder %eax %ecx))
                 (set! %eax %ecx)
                 (set! %ecx %edx)
                 (goto loop))
  (define (end)  (printf "result: ~s\n" %eax)
                 (return %eax))
  (main))

Exceptions

Racket has exceptions which are used in the usual way, and with-handlers to catch them. In fact, any value can be raised, not just exceptions. For example:

(define (list-product l)
  (with-handlers ([void identity])
    (let loop ([l l] [r 1])
      (cond [(null? l) r]
            [(zero? (car l)) (raise 0)]
            [else (loop (cdr l) (* r (car l)))]))))

Continuations

Racket has full continuations, of all kinds, including delimited and not. That's plenty of control flow...

And more

Given that Racket has macros, and continuations, and a zillion other features, it is easy to implement new control flow expressions, so any list will not be exhaustive.

Raku

(formerly Perl 6)

Control exceptions

Control flow is extensible in Raku; most abnormal control flow (including the standard loop and switch exits) is managed by throwing control exceptions that are caught by the code implementing the construct in question. Warnings are also handled via control exceptions, and turn into control flow if the dynamic context chooses not to resume after the warning. See [S04/Control exceptions] for more information.

Phasers

Phasers are blocks that are transparent to the normal control flow but that are automatically called at an appropriate phase of compilation or execution. The current list of phasers may be found in [S04/Phasers].

goto

TOWN: goto TOWN;

Labels that have not been defined yet must be enclosed in quotes.

REBOL

REBOL [
	Title: "Flow Control"
	URL: http://rosettacode.org/wiki/Flow_Control_Structures
]

; return -- Return early from function (normally, functions return
; result of last evaluation).

hatefive: func [
	"Prints value unless it's the number 5."
	value "Value to print."
][
	if value = 5 [return "I hate five!"]
	print value
]

print "Function hatefive, with various values:"
hatefive 99
hatefive 13
hatefive 5
hatefive 3

; break -- Break out of current loop.

print [crlf "Loop to 10, but break out at five:"]
repeat i 10 [
	if i = 5 [break]
	print i
]

; catch/throw -- throw breaks out of a code block to enclosing catch.

print [crlf "Start to print two lines, but throw out after the first:"]
catch [
	print "First"
	throw "I'm done!"
	print "Second"
]

; Using named catch blocks, you can select which catcher you want when throwing.

print [crlf "Throw from inner code block, caught by outer:"]
catch/name [
	print "Outer catch block."
	catch/name [
		print "Inner catch block."
		throw/name "I'm done!" 'Johnson
		print "We never get here."
	] 'Clemens
	print "We never get here, either."
] 'Johnson

; try

div: func [
	"Divide first number by second."
	a b
	/local r "Result"
][
	if error? try [r: a / b] [r: "Error!"]
	r ; Functions return last value evaluated.
]

print [crlf "Report error on bad division:"]
print div 10 4
print div 10 2
print div 10 1
print div 10 0


Relation

  • stop ends execution of the entire program

REXX

break

(See the leave statement.)

call

The call statement immediately transfers control to a named subroutine, and the call statement may have any number (or none) parameters.   (However, most REXXes have some practical limit to the number of arguments, usually at least 50).

The named subroutine may or may not return a   result   (which is similar to a return code, but REXX allows character strings as well).

(Also, see function invocation and signal statement below.)

call  routineName                      /*no arguments passed to routine.*/
call  routineName  50                  /*one argument (fifty) passed.   */
call  routineName  50,60               /*two arguments        passed.   */
call  routineName  50, 60              /*(same as above)                */
call  routineName  50 ,60              /*(same as above)                */
call  routineName  10*5 , 8**4 - 4     /*(same as above)                */
call  routineName  50 , , , 70         /*4 args passed, 2nd&3rd omitted.*/
                                       /*omitted args are   NOT  null.  */
call  routineName  ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted.    */
call   date                            /*looks for DATE internally first*/
call  'DATE'                           /*  "    "    "  BIF | externally*/

real-life example:

numeric digits 1000                 /*prepare for some gihugeic numbers.*/
...
n=4
call factorial n
say n'!=' result
exit
/*──────────────────────────────────FACTORIAL subroutine────────────────*/
factorial: parse arg x
!=1
           do j=2  to x
           !=!*j
           end   /*j*/
return !

case

(See the select statement below.)

exceptions

(See the signal statement and raising conditions below.)

exit

The exit statement terminates the running (REXX) program and passes control to the invoking program (it could be the shell/host/supervisor program).

If an expression is coded, it normally is used to set the result (if a REXX program) or return code (also called RetCode, RC, completion code, or other such names).

When using the exit with an expressing to pass control to the operating system (i.e., exiting a REXX program), some operating systems require the expression to be a whole number within a certain range (often with a no expression or a [null] expression, which is usually taken to mean a return code of 0).

If the expression is a number, it is normalized to the current numeric digits.

(Also, see the return statement below.)

exit

exit  expression

function invocation

A function invocation (similar to a call) immediately transfers control to a named function (subroutine), and the function/subroutine invocation statement may have any number (or none) parameters.   (However, most REXXes have some practical limit to the number of arguments, usually at least 50).

(In REXX, the only difference between a function and a subroutine is that a function returns a   result   --- that is, some value is returned, which may be null)

The named function/subroutine must return a   result   (which is similar to a return code, but REXX allows character strings as well).

If no   result   is returned, REXX generates a syntax error   (which may be trapped via the signal on syntax instruction).

(Also, see the call statement above.)

numeric digits 1000                 /*prepare for some gihugeic numbers.*/
...
n=4
say n'!='  factorial(n)
exit
/*──────────────────────────────────FACTORIAL subroutine────────────────*/
factorial: parse arg x
!=1
           do j=2  to x
           !=!*j
           end   /*j*/
return !

iterate

The iterate statement immediately transfer control to the innermost active   do   statement in which the iterate statement is located, that is, it (may) iterates (increments or decrements) the named REXX variable (if any) that is specified on the   do   statement.   The iterate statement can also specify which   do   loop is to be iterated if there is a named variable on the do loop.

(All indentations in REXX are merely cosmetic and are used for readability.}

sum=0
        do j=1  to 1000
        if j//3==0 | j//7==0  then iterate
        sum=sum+j
        end   /*j*/

           /*shows sum of 1k numbers except those divisible by 3 or 7.*/
say 'sum='sum
...
numeric digits 5000
prod=0
                  do k=1  to 2000
                        do m=1  to k
                        if m>99  then iterate k
                        prod=prod*m
                        end   /*m*/
                  end      /*k*/ 
say 'prod=' prod

go to

(See the signal statement.)

leave

The leave statement transfer control to the next REXX statement following the   end   statement of the current (active)   do   loop in which the leave statement is located.   The leave statement can also specify which do loop is to be left (terminated) if the do loop has a named variable.

  do j=1  to 10
  say 'j=' j
  if j>5  then leave
  say 'negative j='  (-j)
  end   /*j*/

say 'end of the DO loop for j.'

ouch=60
sum=0
                do k=0  to 100  by 3
                say 'k=' k
                           do m=1  to k
                           if m=ouch  then leave k
                           sum=sum+m
                           end   /*m*/
                end              /*k*/
say 'sum=' sum

raising conditions

(REXX) conditions can be raised by causing some kind of "failure" or triggering event   (such as division by zero).

A signal statement must have been issued previous to the event being triggered to enable trapping.

It should be noted that some older REXXes don't support all the signal variants.

(Also, see the signal statement below.)

...
signal on syntax
...
y=4 - 4
x=66
say x/y                  /*divide x by y.*/
say "yup, that's a divide by zero, by gum."
exit

syntax: say

/* We can now possibly do some repair work , but most people trap */
/* the condition, display where it happened, the REXX sourceline  */
/* (the actual REXX statement),  which condition was triggered,   */
/* display any other pertinent REXX variables, which line in the  */
/* REXX program, and then (usually) exit with some kind of error  */
/* message and error code indicator.                              */
/* Note:  the "name" of the REXX program isn't quite accurate,    */
/* rather, it is the name that was invoked (called by), which may */
/* be different name than the actual program being executed.      */

say '──────────────────────error!─────────────────────────'
say 'that division (above) will cause control to get here.'
parse source . . fid .
say;  say  'REXX raised a SYNTAX error in program:' fid
say;  say  'it occurred on line' sigl
say;  say  'the REXX statement is:'     /*put it on separate line.*/
      say  sourceline(sigl)
say;  say  'which code:' condition('C') "error"
say;  say  'error code:' condition('D')
say;  say  "Moral: don't do that."
exit 13
Output:
──────────────────────error!─────────────────────────
that division (above) will cause control to get here.

REXX raised a SYNTAX error in program: D:\OOPSsay.REX

it occurred on line 6

the REXX statement is:
say x/y                  /*divide x by y.*/

which code: SYNTAX error

error code: Error 42.3: Arithmetic overflow; divisor must not be zero

Moral: don't do that.

A note regarding the following REXXes:

  • PC/REXX
  • Personal REXX
  • R4
  • ROO
  • CMS REXX
  • TSO REXX
  • ooRexx
  • Regina REXX

Three conditions allow to specify CALL ON condition: ERROR, FAILURE, and HALT (there may be others).

From the corresponding condition handlers one can RETURN to the instruction following the instruction/command where the condition was encountered.
A short example:

Say 'Interrupt this program after a short while'
Call on halt 
Do i=1 To 10000000
  j=i**2+1
  End
halt: Say i  j
Return

return

The return statement terminates the running (REXX) program (which could be a subroutine or function) and passes control to the invoking program (it could be the shell/host/supervisor program).

If no internal subroutine or function is active,   return   is equivalent to   exit.

If a subroutine is active (a call was used), control goes to the instruction after the call statement.

If a function is active (a function reference was used) control goes back to the expression evaluation using the value resulting from the   return   expression.

(Also, see the exit statement above.)

return

return  expression

select

The select statement is used to conditionally test for cases to selectively execute REXX statement(s).

...
prod=1
a=7               /*or somesuch.*/
b=3               /*  likewise. */

op='**'           /*or whatever.*/
...
    select
    when op=='+'         then  r=a+b           /*add.                   */
    when op=='-'         then  r=a-b           /*subtract.              */
    when op=='∙'         then do; r=a*b; prod=prod*r; end    /*multiply.*/
    when op=='*'         then  r=a*b           /*multiply.              */
    when op=='**'        then  r=a**b          /*power (exponentiation) */
    when op=='/'  & b\=0 then  r=a/b           /*divide.                */
    when op=='%'  & b\=0 then  r=a/b           /*interger divide.       */
    when op=='//' & b\=0 then  r=a/b           /*modulus (remainder).   */
    when op=='||'        then  r=a||b          /*concatenation.         */
    when op=='caw'       then  r=xyz(a,b)      /*call the XYZ subroutine*/
    otherwise                  r='[n/a]'       /*signify not applicable.*/
    end   /*select*/

say 'result for'   a   op   b   "="   r

signal

The signal statement can be thought of as a GO TO or JUMP statement, however, on issuance of a signal statement, all active do loops and select structures are terminated.   Essentially, that means that there is no real way to re-enter a do loop (or a select structure) once a signal statement is used.

Once a signal statement is executed (or invoked), control passed to the first occurrence of the label specified (in REXX, more than one label with the same name isn't considered an error).   The label can be any combination of letters, digits, periods, and some special symbols, the most common are $, #, @, !, ?, and _ (underscore or underbar).   Some versions of REXX (CMS, PC/REXX, Personal REXX, TSO, R4, ROO) also allow the cent sign (¢), some of those REXXes support the British pound (currency) symbol (£).

The signal statement is also used to transfer control in case of some specific conditions:

  • when an I/O stream (could be a file) isn't ready.
  • when the REXX program used a variable that isn't defined.
  • when a REXX syntax error occurs.
  • when the program is halted (this depends on the operating system):
  • Ctrl-Alt-Del     under VM/CMS or MVS/TSO (generic names)
  • HX                 under VM/CMS or MVS/TSO (generic names)
  • PA1               under VM/CMS or MVS/TSO (generic names)
  • Ctrl-c             some Unix, BSD variants
  • Del   (key)     most System V variants
  • SIGINT           (SIGnal INTerrupt) some variants of UNIX
  • kill(1)               from the command line (same as above)
  • signal(3)         from a program (same as above)
  •           [to be sure, check with your operating system documentation]
  • when there is a loss of decimal digits   (for the newer REXXes).
  • when a command executed returns an error return code [other than 0 (zero)].
  • when a command executed indicates a failure.

It should be noted that some older REXXes don't support all the signal variants.

(Also, see raising conditions above.)

...
signal on error
signal on failure
signal on halt
signal on lostdigits      /*newer REXXes.*/
signal on notready
signal on novalue
signal on syntax

signal off error
signal off failure
signal off halt
signal off lostdigits     /*newer REXXes.*/
signal off notready
signal off novalue
signal off syntax
...
signal on novalue
...
x=oopsay+1                /* ◄─── this is it.*/
exit

novalue: say
say '───────────────────────────error!─────────────────────────────────'
say 'that reference to  oopsay  (above) will cause control to get here.'
parse source . . fid .
say;  say  'REXX raised a NOVALUE error in program:' fid
say;  say  'it occurred on line' sigl
say;  say  'the REXX statement is:'     /*put it on separate line.*/
      say  sourceline(sigl)
say;  say  'which code:' condition('C') "error"
say;  say  'REXX variable:' condition('D')
say;  say  "Moral: shouldn't do that."
Output:
───────────────────────────error!─────────────────────────────────
that reference to  oopsay  (above) will cause control to get here.

REXX raised a NOVALUE error in program: D:\flow_sig.rex

it occurred on line 20

the REXX statement is:
x=oopsay+1                /* ◄─── this is it.*/

which code: NOVALUE error

REXX variable: OOPSAY

Moral: shouldn't do that.

Ring

i = 1
while true
      see i + nl
      if i = 10 see "Break!" exit ok
      i = i + 1 
end

Ruby

return

Return from the currently executing method to the caller.

loop control

Ruby's loop control statements are: break, next, redo and retry. Break and next are obvious. Redo and retry both restart the current loop iteration, but retry first reevaluates the condition. They can control while, until, for loops and iterators.

exceptions

Use raise to throw an exception. You catch exceptions in the rescue clause of a begin...end block.

begin
  # some code that may raise an exception
rescue ExceptionClassA => a
  # handle code
rescue ExceptionClassB, ExceptionClassC => b_or_c
  # handle ...
rescue
  # handle all other exceptions
else
  # when no exception occurred, execute this code
ensure
  # execute this code always
end

There is also a rescue modifier (example from the Pickaxe book):

values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]

catch and throw

break will only break out of a single level of loop. You can surround code in a catch block, and within the block you can throw a string or symbol to jump out to the end of the catch block (Ruby's GOTO, I suppose):

def some_method
  # ...
  if some_condition
    throw :get_me_out_of_here
  end
  # ...
end

catch :get_me_out_of_here do
  for ...
    for ...
      some_method
    end
  end
end

puts "continuing after catching the throw"

yield

yield passes control from the currently executing method to its code block.

SAS

/* GOTO: as in other languages
   STOP: to stop current data step */
data _null_;
	n=1;
	p=1;
L1:
	put n p;
	n=n+1;
	if n<=p then goto L1;
	p=p+1;
	n=1;
	if p>10 then stop;
	goto L1;

run;

/* LINK: equivalent of GOSUB in BASIC
   RETURN: after a LINK, or to return to the beginning of data step */
data _null_;
input a b;
link gcd;
put a b gcd;
return;

gcd:
	_a=a;
	_b=b;
	do while(_b>0);
	_r=mod(_a,_b);
	_a=_b;
	_b=_r;
	end;
	gcd=_a;
	return;

cards;
2 15
533 221
8 44
;
run;

Scala

Library: Scala
import Goto._
import scala.util.continuations._

object Goto {

  case class Label(k: Label => Unit)

  private case class GotoThunk(label: Label) extends Throwable

  def label: Label @suspendable =
    shift((k: Label => Unit) => executeFrom(Label(k)))

  def goto(l: Label): Nothing =
    throw new GotoThunk(l)

  private def executeFrom(label: Label): Unit = {
    val nextLabel = try {
      label.k(label)
      None
    } catch {
      case g: GotoThunk => Some(g.label)
    }
    if (nextLabel.isDefined) executeFrom(nextLabel.get)
  }

}

Sidef

goto

say "Hello"
goto :world
say "Never printed"
@:world
say "World"
Output:
Hello
World

SSEM

Indirect absolute jump

The 000 n to CI instruction loads the value stored at address n into the Current Instruction register. For instance,

00101000000000000000000000000000      20 to CI
...
01010000000000000000000000000000  20. 10

loads the number 10 into CI. Since CI is incremented after the instruction has been executed, rather than before, this fragment will cause execution to jump to address 11.

Indirect relative jump

100 Add n to CI increases the number in the CI register by the value stored at address n.

00101000000001000000000000000000      Add 20 to CI
...
01010000000000000000000000000000  20. 10

adds 10 to CI. Once again, CI is incremented after the instruction has been executed: so the machine actually jumps ahead by 11 instructions.

Stata

Mata has a goto statement. It may be used to break nested loops, or to convert easily Fortran code to Mata.

As an example, let's find a Pythagorean triple a,b,c such that a+b+c=n, where n is given. Here goto is used to break the two loops when such a triple is found. A return can be used in such situations, unless one has to do further computations after the loop.

mata
function pythagorean_triple(n) {
	for (a=1; a<=n; a++) {
		for (b=a; b<=n-a; b++) {
			c=n-a-b
			if (c>b & c*c==a*a+b*b) {
				printf("%f %f %f\n",a,b,c)
				goto END
			}
		}
	}
	END:
}

pythagorean_triple(1980)
165 900 915

Tcl

after

The after facility can be used to execute some code at some future time asynchronously, like this

after 1000 {myroutine x}

which will call "myroutine" with parameter "x" 1000ms from 'now'; no matter what other code might be running at the time (i.e. "after"; schedules the execution, then returns and continues program flow with the following code).

The scheduled task can be removed from the scheduler for example with

after cancel myroutine

(other ways are possible).

The correct way to schedule some regularly recurring task in TCL is to incorporate a self-scheduling at the end of the routine. For example the following will produce a clock whose display is updated once a second:

package require Tk
proc update {} {
    .clockface configure -text [clock format [clock seconds]]
    after 1000 update ; # call yourself in a second
}
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
update

loop control

Tcl has the break command to abort the current loop (for/foreach/while) and the continue command to skip to the next loop iteration.

exception

Tcl's catch command can be used to provide a basic exception-handling mechanism:

if {[catch { ''... code that might give error ...'' } result]} {
    puts "Error was $result"
} else {
    ''... process $result ...''
}

Tcl 8.6 also has a trytrapfinally structure for more complex exception handling.

try {
    # Just a silly example...
    set f [open $filename]
    expr 1/0
    string length [read $f]
} trap {ARITH DIVZERO} {} {
    puts "divided by zero"
} finally {
    close $f
}

custom control structures

A novel aspect of Tcl is that it's relatively easy to create new control structures (more detail at http://wiki.tcl.tk/685). For example, this example defines 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
}

Now we can use it to print the length of each line of file "mydata.txt":

forfilelines myline mydata.txt {
    puts [string length $myline]
}

Tiny BASIC

    REM TinyBASIC has only two control flow structures: goto and gosub
    LET N = 0
 10 LET N = N + 1
    PRINT N
    IF N < 10 THEN GOTO 10
    
    LET R = 10
    
 15 IF N < 10000 THEN GOSUB 20
    IF N > 10000 THEN GOTO 30
    GOTO R + 5    REM goto can be computed
     
 20 LET N = N * 2
    PRINT N
    RETURN    REM gosub returns to where it was called from
              REM meaning it can be called from multiple
              REM places in the program
        
 30 LET N = 0
 40 GOSUB 105-N    REM gosub can be computed as well
    IF N <= 5 THEN GOTO 40
    END
    
100 PRINT "ZERO"
101 PRINT "1"
102 PRINT "22"
103 PRINT "333"
104 PRINT "4444"
105 PRINT "55555"
    LET N = N + 1
    RETURN    REM one return can serve several gosubs

Visual Basic .NET

Goto

This skips the line that changes the value of x to 5.

  Sub bar2()
      Dim x = 0
      GoTo label
      x = 5
label:
      Console.WriteLine(x)
  End Sub

On Error Goto

This branches in the event of an error. Usually there is an Exit (Sub|Function) to separate the normal code from the error handling code

   Sub foo()
       On Error GoTo label
       'do something dangerous
       Exit Sub
label:
       Console.WriteLine("Operation Failed")
   End Sub

This style of code is rarely used.

On Error Resume Next

This performs a sequence of actions. If any action fails, the exception is discarded and next operation is performed.

Sub foo2()
    On Error Resume Next
    Operation1()
    Operation2()
    Operation3()
    Operation4()
End Sub

This style of code is rarely used.

Return / Exit Sub

This shows the classical and modern syntax for exiting a sub routine early.

Sub Foo1()
    If Not WorkNeeded() Then Exit Sub
    DoWork()
End Sub
 
Sub Foo2()
    If Not WorkNeeded() Then Return
    DoWork()
End Sub

Return value / Exit Function

This shows the classical and modern syntax for exiting a function early. There is an implied variable with the same name as the function. This variable is write-only.

Function Foo3()
    Foo3 = CalculateValue()
    If Not MoreWorkNeeded() Then Exit Function
    Foo3 = CalculateAnotherValue()
End Function
 
Function Foo4()
    Dim result = CalculateValue()
    If Not MoreWorkNeeded() Then Return result
    Return CalculateAnotherValue()
End Function

Wren

Wren has three control flow statements, break, continue and return.

Break exits from the nearest enclosing for or while loop and transfers control to the next statement after that.

Continue (from v0.4.0) jumps to the next iteration of the nearest enclosing for or while loop.

Return exits from a method or function and can be optionally followed by a value. Controls returns to the caller. It can also be used to exit the current module from 'top level' code.

Whilst part of the standard library rather than the language itself, the Fiber.abort method can be used to exit the script when an error occurs. However, it is possible to catch the error using Fiber.try.

Fiber.suspend pauses the current fiber and stops the interpreter. Control returns to the host application, if there is one. However, execution of the script can be resumed later by storing a reference to the current fiber and then calling that.

The following code demonstrates each of the above apart from Fiber.suspend which simply exits a CLI script.

var func = Fn.new { |n|
    var i = 1
    while (true) {
        if (i == 1) {
            i = i + 1
            continue // jumps to next iteration
        }
        System.print(i)
        if (i == n) break // exits while loop
        i = i + 1
    }
    if (n < 3) return // exits function
    System.print(n + 1)
}

var fiber = Fiber.new {
    Fiber.abort("Demo error") // error occurred, abort script
}

var a = [2, 3]
for (n in a) {
    func.call(n)
    if (n > 2) return // end module and hence the script as it's a single module script
    var error = fiber.try() // catch any error
    System.print("Caught error: " + error)
}
Output:
2
Caught error: Demo error
2
3
4

XPL0

XPL0 does not have a goto statement, but it has other similar statements. Its quit statement jumps out of a loop block. A return jumps out of a procedure, or a function where it's also used to return the numerical result of the function. A return in the main procedure terminates a program. An exit statement terminates a program from any location. Like the return statement, it can send an optional value, in this case to the operating system.

Some routines called intrinsics that are automatically included in a program also affect flow control. The Abort intrinsic is like the exit statement except it does not return a value. (It's deprecated in preference to exit.) The Restart intrinsic, which can be called from anywhere, restarts a program at its beginning. (The Rerun intrinsic is used to distinguish a restart from a normal start.) Certain errors such as divide-by-zero or attempting to open a non-existent file abort a program. The Trap intrinsic can disable this feature. It's normally used with the GetErr intrinsic, which provides a way to detect these kinds of errors and handle them without aborting.

Yabasic

Works with: QuickBasic version 4.5
gosub subrutina

label bucle
print "Bucle infinito"
goto bucle
end

label subrutina
print "En subrutina"
wait 10
return
end

Z80 Assembly

JP and JR

This is the equivalent of GOTO in BASIC, in that after the jump takes place, the CPU has no way of knowing where it came from.

  • JP takes three bytes, one for the jump itself, and two for the address. This instruction can jump conditionally based on the status of the zero, carry, sign, and overflow/parity flags. (On Game Boy, there are no sign or overflow/parity flags so those jumps won't work even for JP)
  • JR is a "short jump" that is program-counter relative. This instruction takes two bytes - one for the jump, and the second is an 8-bit signed offset. The offset represents how many bytes forward or backward to jump - JR can only travel forward 127 bytes and backward 128 bytes, and cannot branch based on the sign or overflow/parity flags - only zero and carry.

Breaking out of a loop

A subroutine that loops is often escaped with a conditional return, or, if it needs to unwind the stack frame, a conditional jump to an unconditional return.

PrintString:
ld a,(hl)       ;HL is our pointer to the string we want to print
cp 0            ;it's better to use OR A to compare A to zero, but for demonstration purposes this is easier to read.
ret z           ;return if accumulator = zero
call PrintChar  ;prints accumulator's ascii code to screen - on Amstrad CPC for example this label points to memory address &BB5A
inc hl          ;next char
jr PrintString  ;jump back to the start of the loop. RET Z is our only exit.

In the above example, the stack was never modified (besides the CALL pushing the return address) so RET Z was safe to use. Conditional returns are not safe to use if the stack needs to be unwound prior to exiting, since there's no way to conditionally unwind the stack without conditionally jumping to a section of code that does just that. In which case you don't need the return to be conditional anyway. This contrived example shows this in action.

foo:
push af
bar:
ld a,(hl)
cp 255
jr z,exit
inc hl
jr bar

exit:
pop af
ret

DJNZ

DJNZ stands for "decrement, jump if nonzero." This is the equivalent of x86's LOOP command - as it subtracts 1 from the B register (just B, not BC) and if it's nonzero, jumps to a specified signed 8-bit offset. (It's better to use a label and let the assembler compute the offset for you.) Although this is usually used for looping, it can also jump forward. The same distance limits of JR apply to DJNZ as well. DJNZ cannot be made conditional based on flags, and it doesn't actually change the flags the same way DEC B would.

(Game Boy doesn't have this instruction - you'll have to use a combination of DEC B and JR NZ)

loop:
    ;your code goes here
    DJNZ loop

Block Instructions

These instructions repeat until BC equals zero. They're useful for doing the same thing in a row, but have one-off equivalents that are faster. However, you can often save space by using these, especially if you can't hardcode a fixed repetition count before using one.

LDIR is the equivalent of memcpy() in C and rep movsb in x86. It loads from the address stored in HL and stores in the address pointed to by DE, increments both HL and DE, decrements BC, and repeats if BC doesn't equal zero.

Essentially it's equivalent to the code below, except in the real LDIR the accumulator isn't actually altered in any way.

_LDIR:
ld a,(hl)
ld (de),a
inc hl
inc de
dec bc
ld a,b
or c         ;compare BC to zero
jr nz,_LDIR  ;Game Boy doesn't have LDIR so you'll have to use this code instead.

There are several others that work in a similar fashion, such as:

  • LDDR - equivalent of x86's REP MOVSB with direction flag set
  • CPIR - equivalent of x86's REPNZ SCASB with direction flag clear
  • CPDR - equivalent of x86's REPNZ SCASB with direction flag set
  • OTIR - equivalent of x86's REP OUTSB with direction flag clear
  • OTDR - equivalent of x86's REP OUTSB with direction flag set
  • INIR - equivalent of x86's REP INSB with direction flag clear
  • INDR - equivalent of x86's REP INSB with direction flag set

zkl

continue; continue(n);  // continue nth nested loop
break; break(n);  // break out of nth nested loop
try{ ... }catch(exception){ ... } [else{ ... }]
onExit(fcn);  // run fcn when enclosing function exits

zkl has state machines for functional style stream processing. There are some special values that machines can return for flow control:

Void.Again    // call the machine again with next value
Void.Drop     // drop an item and call next machine
(Void.Read,n) // read the next n items and pass to the next machine
Void.Skip     // ignore this item, ie continue
(Void.Skip,v) //   value is v
Void.Stop     // stop, ie break
(Void.Stop.v) //   value is v
(Void.write,x,y,z) // write x,y,x to sink

As an example, decode URL strings:

urlText.pump(String,
   fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) },
   fcn(_,b,c){(b+c).toInt(16).toChar()})

has two machines. The second machine only runs if "%" is seen.

urlText:="http%3A%2F%2Ffoo.com%2Fbar";
urlText.pump(...).println();
Output:
http://foo.com/bar