Flow-control structures: Difference between revisions

m
→‎{{header|Ada}}: added 'return'
m (→‎{{header|Ada}}: added 'return')
 
(16 intermediate revisions by 9 users not shown)
Line 1:
{{Task|Control Structures}}
{{Control Structures}}
[[Category:Flow control]]
 
;Task:
Line 20 ⟶ 21:
===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.
<langsyntaxhighlight lang="11l">V n = 10
Int result
 
Line 31 ⟶ 32:
L.was_no_break
result = -1
print(‘No odd factors found’)</langsyntaxhighlight>
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 ⟶ 39:
===Unconditional Branch (B)===
To perform a 'goto'.
<langsyntaxhighlight lang="360asm">
B TESTPX goto label TESTPX
BR 14 goto to the address found in register 14
</syntaxhighlight>
</lang>
===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'.
<langsyntaxhighlight lang="360asm">
LA 15,SINUSX load in reg15 address of function SINUSX
BALR 14,15 call the subroutine SINUX and place address RETPNT in reg14
Line 52 ⟶ 53:
...
BR 14 return to caller
</syntaxhighlight>
</lang>
 
===Conditional Branch (BC)===
Fistly a compare instruction set the condition code (cc), secondly a conditional branch is performed.
<langsyntaxhighlight lang="360asm">
L 4,A Load A in register 4
C 4,B Compare A with B
Line 65 ⟶ 66:
BNL TESTGE Branch on Not Low if A>=B then goto TESTGE
BNE TESTNE Branch on Not Equal if A<>B then goto TESTNE
</syntaxhighlight>
</lang>
===Branch on Count (BCT)===
To perform unconditional loops.
<langsyntaxhighlight lang="360asm">
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
</syntaxhighlight>
</lang>
===Branch on Index (BX.)===
BXLE to perform loops in old Fortran style with 3 registers.
<langsyntaxhighlight lang="360asm">
* do i=1 to 8 by 2
L 3,1 r3 index and start value 1
Line 84 ⟶ 85:
... loop 4 times (r3=1,3,5,7)
BXLE 3,4,LOOPI r3=r3+r4; if r3<=r5 then loop
</syntaxhighlight>
</lang>
BXH to perform backward loops with 3 registers.
<langsyntaxhighlight lang="360asm">
* do i=8 to 1 by -2
L 3,1 r3 index and start value 8
Line 94 ⟶ 95:
... loop 4 times (r3=8,6,4,2)
BXH 3,4,LOOPI r3=r3+r4; if r3>r5 then loop
</syntaxhighlight>
</lang>
 
=={{header|6502 Assembly}}==
Line 100 ⟶ 101:
===JMP===
The jump instruction immediately jumps to any address:
<langsyntaxhighlight lang="6502asm"> JMP $8000 ;immediately JuMP to $8000 and begin executing
;instructions there.</langsyntaxhighlight>
The indirect jump instruction immediately jumps to the address contained in the address:
<langsyntaxhighlight lang="6502asm"> JMP ($8000) ;immediately JuMP to the address in memory locations
;$8000 and $8001</langsyntaxhighlight>
 
===JSR===
The jump to subroutine instruction pushes the address of the next instruction minus one onto the stack and jumps to any address:
<langsyntaxhighlight lang="6502asm"> JSR $8000 ;Jump to SubRoutine</langsyntaxhighlight>
A return from subroutine instruction pops the return address off the stack, adds one, and jumps to that location:
<langsyntaxhighlight lang="6502asm"> RTS ;ReTurn from Subroutine</langsyntaxhighlight>
 
===NMI===
Line 131 ⟶ 132:
 
===goto===
<langsyntaxhighlight lang="ada"><<Top>>
Put_Line("Hello, World");
goto Top;</langsyntaxhighlight>
 
===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:
<langsyntaxhighlight lang="ada">Outer:
loop
-- do something
loop
--if doFinished somethingthen
loop
-- do something else
exit Outer; -- exits both the inner and outer loops
end loopif;
-- 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===
A sequence of operation can be aborted with an asynchronous transfer of control to an alternative:
<langsyntaxhighlight lang="ada">select
delay 10.0;
Put_Line ("Cannot finish this in 10s");
Line 153 ⟶ 177:
-- do some lengthy calculation
...
end select;</langsyntaxhighlight>
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 164 ⟶ 188:
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.===
<langsyntaxhighlight lang="algol68">(
FOR j TO 1000 DO
FOR i TO j-1 DO
Line 175 ⟶ 199:
OD;
done: EMPTY
);</langsyntaxhighlight>
===Multi way jump using labels and '''EXIT''' to return result ===
<langsyntaxhighlight lang="algol68">STRING medal = (
[]PROC VOID award = (gold,silver,bronze);
 
Line 188 ⟶ 212:
);
 
print(("Medal awarded: ",medal, new line));</langsyntaxhighlight>
===Another use is to implement finite state machines ===
<langsyntaxhighlight lang="algol68">STRING final state = (
INT condition;
PROC do something = VOID: condition := 1 + ENTIER (3 * random);
Line 210 ⟶ 234:
"State N"
);
print(("Final state: ",final state, new line));</langsyntaxhighlight>
===ALGOL 68G implements a Refinement Preprocessor to aid with top down code development ===
<langsyntaxhighlight lang="algol68"># example from: http://www.xs4all.nl/~jmvdveer/algol.html - GPL #
determine first generation;
WHILE can represent next generation
Line 233 ⟶ 257:
printf (($lz","3z","3z","2z-d$, current,
$xz","3z","3z","2z-d$, previous,
$xd.n(real width - 1)d$, current / previous)).</langsyntaxhighlight>
{{out}}
<pre>
Line 248 ⟶ 272:
=={{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".
<langsyntaxhighlight lang="algolw">begin
integer i;
integer procedure getNumber ;
Line 265 ⟶ 289:
writeon( "negative" );
endProgram:
end.</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
<langsyntaxhighlight ARMlang="arm Assemblyassembly">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.
Line 279 ⟶ 303:
 
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.</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, calling Label1
Gosub, Label1
MsgBox, Label1 subroutine finished
Line 295 ⟶ 327:
Label2:
MsgBox, Label2 will not return to calling routine
Return</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 301 ⟶ 333:
The [awk] programming language is data driven. However, Awk has ''break'' and ''continue'' for loop control, as in C.
 
<langsyntaxhighlight lang="awk">$ awk 'BEGIN{for(i=1;;i++){if(i%2)continue; if(i>=10)break; print i}}'
2
4
6
8</langsyntaxhighlight>
 
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">
<lang BASIC256>
gosub subrutina
 
Line 322 ⟶ 354:
return
end
</syntaxhighlight>
</lang>
 
 
Line 328 ⟶ 360:
{{works with|BBC BASIC for Windows}}
BBC BASIC has '''GOSUB''' and '''GOTO''' but they are deprecated.
<langsyntaxhighlight lang="bbcbasic"> GOSUB subroutine
(loop)
Line 338 ⟶ 370:
PRINT "In subroutine"
WAIT 100
RETURN</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="bracmat"> ( LOOP
= out$"Hi again!"
& !LOOP
)
& out$Hi!
& !LOOP</langsyntaxhighlight>
{{out}}
<pre>Hi!
Line 359 ⟶ 391:
===goto===
One common use of goto in C is to break out of nested loops.
<langsyntaxhighlight lang="c">int main()
{
int i,j;
Line 371 ⟶ 403:
out:
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
===return===
terminates the function and returns control to the caller.
<langsyntaxhighlight lang="csharp">int GetNumber() {
return 5;
}</langsyntaxhighlight>
===throw===
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.
<langsyntaxhighlight lang="csharp">try {
if (someCondition) {
throw new Exception();
Line 391 ⟶ 423:
} finally {
cleanUp();
}</langsyntaxhighlight>
===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.
<langsyntaxhighlight lang="csharp">public static void Main() {
foreach (int n in Numbers(i => i >= 2) {
Console.WriteLine("Got " + n);
Line 407 ⟶ 439:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 416 ⟶ 448:
===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.
<langsyntaxhighlight lang="csharp">async Task DoStuffAsync() {
DoSomething();
await someOtherTask;//returns control to caller if someOtherTask is not yet finished.
DoSomethingElse();
}
</syntaxhighlight>
</lang>
===break and continue===
<code>continue</code> causes the closest enclosing loop to skip the current iteration and start the next iteration immediately.<br/>
Line 428 ⟶ 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/>
Because the label must be in scope, <code>goto</code> cannot jump inside of a loop.
<langsyntaxhighlight lang="csharp">while (conditionA) {
for (int i = 0; i < 10; i++) {
if (conditionB) goto NextSection;
Line 434 ⟶ 466:
}
}
NextSection: DoOtherStuff();</langsyntaxhighlight>
 
=={{header|C++}}==
=== goto ===
{{works with|GCC|3.3.4}}
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main()
Line 446 ⟶ 478:
std::cout << "Hello, World!\n";
goto LOOP;
}</langsyntaxhighlight>
 
Note that "goto" may also be used in conjunction with other forms of branching.
Line 454 ⟶ 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.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <ostream>
 
Line 524 ⟶ 556:
<< "inside foobar(). Thus this catch-all block never gets invoked.\n";
}
}</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 546 ⟶ 578:
=== GO TO ===
Basic use:
<langsyntaxhighlight lang="cobol"> PROGRAM-ID. Go-To-Example.
 
PROCEDURE DIVISION.
Line 553 ⟶ 585:
 
GO TO Foo
.</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="cobol"> GO TO First-Thing Second-Thing Third-Thing
DEPENDING ON Thing-To-Do
 
* *> Handle invalid thing...</langsyntaxhighlight>
The previous example is equivalent to:
<langsyntaxhighlight lang="cobol"> EVALUATE Thing-To-Do
WHEN 1
* *> Do first thing...
Line 573 ⟶ 605:
WHEN OTHER
* *> Handle invalid thing...
END-EVALUATE</langsyntaxhighlight>
 
=== ALTER ===
Line 585 ⟶ 617:
 
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
program-id. altering.
Line 624 ⟶ 656:
*> fall through to the exit
exit program.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 638 ⟶ 670:
=== 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.
<langsyntaxhighlight lang="cobol"> PROGRAM-ID. Perform-Example.
 
PROCEDURE DIVISION.
Line 660 ⟶ 692:
Moo.
DISPLAY "Moo"
.</langsyntaxhighlight>
{{out}}
<pre>
Line 673 ⟶ 705:
=={{header|Comal}}==
===Call a procedure===
<langsyntaxhighlight Comallang="comal">myprocedure
END // End of main program
PROC myprocedure
PRINT "Hello, this is a procedure"
ENDPROC myprocedure</langsyntaxhighlight>
 
===Exit a loop===
<langsyntaxhighlight Comallang="comal">LOOP
PRINT "I'm in a loop!"
EXIT
ENDLOOP
PRINT "But i somehow got out of it."</langsyntaxhighlight>
 
===Conditional exit===
<langsyntaxhighlight Comallang="comal">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."</langsyntaxhighlight>
 
===Goto===
<langsyntaxhighlight Comallang="comal">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</langsyntaxhighlight>
 
=={{header|D}}==
=== goto ===
<langsyntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 710 ⟶ 742:
writeln("I'm in your infinite loop.");
goto label1;
}</langsyntaxhighlight>
 
=== Exceptions ===
D supports the try/catch/finally mechanism:
<langsyntaxhighlight lang="d">import std.stdio;
 
class DerivedException : Exception {
Line 735 ⟶ 767:
writeln("finished (exception or none).");
}
}</langsyntaxhighlight>
 
=== Scope guards ===
Line 743 ⟶ 775:
 
For instance:
<langsyntaxhighlight lang="d">import std.stdio;
 
void main(string[] args) {
Line 755 ⟶ 787:
writeln("Gone, but we passed the first" ~
" chance to throw an exception.");
}</langsyntaxhighlight>
 
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 778 ⟶ 810:
 
[[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}}==
Line 785 ⟶ 837:
===CATCH-THROW===
Some Forth implementations have goto, but not the standard. It does have an exception mechanism.
<langsyntaxhighlight lang="forth">: checked-array
CREATE ( size -- ) DUP , CELLS ALLOT
DOES> ( i -- a+i )
Line 797 ⟶ 849:
 
: safe-access ( i -- a[i] )
['] myarray CATCH 1 = IF ." Out of bounds!" 0 THEN ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 806 ⟶ 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...
 
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... <langsyntaxhighlight Fortranlang="fortran"> ...
ASSIGN 1101 to WHENCE !Remember my return point.
GO TO 1000 !Dive into a "subroutine"
Line 817 ⟶ 869:
Common code, far away.
1000 do something !This has all the context available.
GO TO WHENCE !Return whence I came.</langsyntaxhighlight>
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<langsyntaxhighlight Fortranlang="fortran"> ASSIGN 2000 TO WHENCE !Deviant "return" from 1000 to invoke 2000.
ASSIGN 1103 TO THENCE !Desired return from 2000.
GO TO 1000
1103 CONTINUE</langsyntaxhighlight>
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 835 ⟶ 887:
 
===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...<langsyntaxhighlight Fortranlang="fortran"> SUBROUTINE FRED(X,*,*) !With placeholders for unusual parameters.
...
RETURN !Normal return from FRED.
...
RETURN 2 !Return to the second label.
END</langsyntaxhighlight>
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 850 ⟶ 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.
 
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: <langsyntaxhighlight Fortranlang="fortran"> XX:DO WHILE(condition)
statements...
NN:DO I = 1,N
Line 858 ⟶ 910:
statements...
END DO NN
END DO XX </langsyntaxhighlight>
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 883 ⟶ 935:
Still, they are available when using the -lang qb dialect.
This dialect provides the best support for the older QuickBASIC code.
<langsyntaxhighlight lang="freebasic">
'$lang: "qb"
 
Line 898 ⟶ 950:
Return
Sleep
</syntaxhighlight>
</lang>
 
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=64e4e68b1c6ce73341d08ba2d9333c07 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
 
Line 913 ⟶ 965:
Goto LoopIt
 
End</langsyntaxhighlight>
Output:
<pre>
Line 927 ⟶ 979:
===Goto===
Go has goto and labels. The following is an infinite loop:
<langsyntaxhighlight lang="go">func main() {
inf:
goto inf
}</langsyntaxhighlight>
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 939 ⟶ 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:
<langsyntaxhighlight lang="go">import "os"
 
func processFile() {
Line 956 ⟶ 1,008:
// more processing
// f.Close() will get called here too
}</langsyntaxhighlight>
 
===Goroutines===
Line 962 ⟶ 1,014:
 
The following program prints a mix of 1’s and 0’s.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 977 ⟶ 1,029:
fmt.Println("0")
}
}</langsyntaxhighlight>
 
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,
<langsyntaxhighlight lang="go">func answer(phone1, phone2 chan int) {
select {
case <-phone1:
Line 989 ⟶ 1,041:
// talk on phone two
}
}</langsyntaxhighlight>
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===
Line 995 ⟶ 1,047:
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">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
Line 1,001 ⟶ 1,053:
50 PRINT ("Hello" AND (1=2)): REM This does not print
100 PRINT "Endless loop"
110 GOTO 100:REM an unconditional jump</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,007 ⟶ 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.
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Control.Monad.Trans
import Control.Monad.Exit
Line 1,018 ⟶ 1,070:
when (x == 3 && y == 2) $
exitWith ()
putStrLn "Done."</langsyntaxhighlight>
 
=={{header|HicEst}}==
[http://www.HicEst.com More on HicEst's ALARM function]
<langsyntaxhighlight lang="hicest">1 GOTO 2 ! branch to label
 
2 READ(FIle=name, IOStat=ios, ERror=3) something ! on error branch to label 3
Line 1,038 ⟶ 1,090:
8 y = LOG( 0 , *9) ! on error branch to label 9
 
9 ALARM( 999 ) ! quit HicEst immediately</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,053 ⟶ 1,105:
'''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:
<langsyntaxhighlight lang="icon">
if x := every i := 1 to *container do { # * is the 'length' operator
if container[i] ~== y then
Line 1,063 ⟶ 1,115:
else
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
<langsyntaxhighlight lang="icon">
break break next
</syntaxhighlight>
</lang>
breaks out of two levels of loop and re-enters the top of the third-level enclosing loop.
 
Line 1,075 ⟶ 1,127:
'''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
<langsyntaxhighlight lang="icon">
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.
 
Line 1,090 ⟶ 1,142:
'''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:
<langsyntaxhighlight lang="icon">
&error := 1
mayErrorOut()
Line 1,099 ⟶ 1,151:
handleError(&errornumber, &errortext, &errorvalue) # keyword values containing facts about the failure
}
</syntaxhighlight>
</lang>
Various idiomatic simplifications can be applied depending on your needs.
 
'''error throwing'''<br>
Errors can be thrown using the function
<langsyntaxhighlight lang="icon">
runerr(errnumber, errorvalue) # choose an error number and supply the offending value
</syntaxhighlight>
</lang>
 
=={{header|IDL}}==
Line 1,112 ⟶ 1,164:
===goto===
 
<langsyntaxhighlight lang="idl">test:
..some code here
goto, test</langsyntaxhighlight>
 
(This is almost never used)
Line 1,120 ⟶ 1,172:
===on_error===
 
<syntaxhighlight lang ="idl">on_error, test</langsyntaxhighlight>
 
(This resumes at the label <tt>test</tt> if an error is encountered)
Line 1,126 ⟶ 1,178:
===on_ioerror===
 
<syntaxhighlight lang ="idl">on_ioerror, test</langsyntaxhighlight>
 
(Same as <tt>on_error</tt>, but for EOFs and read-errors and such)
Line 1,132 ⟶ 1,184:
===break===
 
<syntaxhighlight lang ="idl">break</langsyntaxhighlight>
 
immediately terminates the innermost current loop (or <tt>if</tt> or <tt>case</tt> etc)
Line 1,138 ⟶ 1,190:
===continue===
 
<syntaxhighlight lang ="idl">continue</langsyntaxhighlight>
 
immediately starts the next iteration of the current innermost loop
Line 1,147 ⟶ 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):
<langsyntaxhighlight lang="j"> 2 * 1 2 3
2 4 6</langsyntaxhighlight>
 
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,160 ⟶ 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''.
 
<langsyntaxhighlight Javalang="java">switch (xx) {
case 1:
case 2:
Line 1,192 ⟶ 1,244:
}
...
} while (thisCondition);</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight Javalang="java">while (condition) {
...
if (someCondition) { continue; /* skip to beginning of this loop */ }
Line 1,221 ⟶ 1,273:
}
....
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,240 ⟶ 1,292:
 
Here is an example from the standard library:
<langsyntaxhighlight lang="jq"># Emit at most one item from the stream generated by g:
def first(g): label $out | g | ., break $out;</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="julia">
function example()
println("Hello ")
Line 1,253 ⟶ 1,305:
println("world")
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 1,262 ⟶ 1,314:
 
Here are some examples:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 1,275 ⟶ 1,327:
if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied")
println("Goodbye!") // won't be executed
}</langsyntaxhighlight>
 
{{out}}
Line 1,290 ⟶ 1,342:
=={{header|Lua}}==
Lua has the <code>break</code>-command to exit loops.
<langsyntaxhighlight lang="lua">i = 0
while true do
i = i + 1
if i > 10 then break end
end</langsyntaxhighlight>
===Tail calls as GOTOs===
The following code - though obviously a useless infinite loop - will '''not''' cause a stack overflow:
<langsyntaxhighlight lang="lua">function func1 ()
return func2()
end
Line 1,305 ⟶ 1,357:
end
 
func1()</langsyntaxhighlight>
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}}==
Line 1,330 ⟶ 1,502:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
try
% do some stuff
Line 1,336 ⟶ 1,508:
% in case of error, continue here
end
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* goto */
block(..., label, ..., go(label), ...);
 
Line 1,346 ⟶ 1,518:
 
/* error trapping */
errcatch(..., error("Bad luck!"), ...);</langsyntaxhighlight>
 
=={{header|MUMPS}}==
===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. <langsyntaxhighlight MUMPSlang="mumps">GOTO LABEL^ROUTINE</langsyntaxhighlight>. This does not affect the subroutine stack, only the program pointer.</p><syntaxhighlight lang MUMPS="mumps">GOTO THERE</langsyntaxhighlight>
 
===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.
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>
<langsyntaxhighlight MUMPSlang="mumps"> Read "Do you really wish to halt (Y/N)?",Q#1
IF Q="Y"!Q="y" HALT</langsyntaxhighlight>
 
===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. <langsyntaxhighlight MUMPSlang="mumps">JOB LABEL^ROUTINE</langsyntaxhighlight>. <langsyntaxhighlight MUMPSlang="mumps">JOB THERE</langsyntaxhighlight> 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>
<syntaxhighlight lang MUMPS="mumps"> JOB LABEL^ROUTINE</langsyntaxhighlight>
 
 
===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>
<langsyntaxhighlight MUMPSlang="mumps">FOR I=1:1:1 QUIT:NoLoop DO YesLoop
QUIT Returnvalue</langsyntaxhighlight>
===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><langsyntaxhighlight MUMPSlang="mumps"> SET A="SET %=$INCREMENT(I)"
SET I=0
XECUTE A
WRITE I</langsyntaxhighlight>
The above block will output "1".
<math>Insert formula here</math>
Line 1,388 ⟶ 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.
 
<langsyntaxhighlight NetRexxlang="netrexx">loop xx = 1 to 10
if xx = 1 then leave -- loop terminated by leave
say 'unreachable'
end</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight NetRexxlang="netrexx">loop xx = 1 to 10 -- xx is the control variable
...
loop yy = 1 to 10 -- yy is the control variable
Line 1,437 ⟶ 1,609:
otherwise do; say 'nl selection'; say '...'; end
end selecting
end vv</langsyntaxhighlight>
 
===ITERATE===
Line 1,444 ⟶ 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.
<langsyntaxhighlight NetRexxlang="netrexx">loop fff = 0 to 9
...
loop xx = 1 to 3
Line 1,452 ⟶ 1,624:
end
...
end fff</langsyntaxhighlight>
 
=={{header|Nim}}==
===Labeled Break & Continue===
Break and continue can be used with block labels to jump out of multiple loops:
<langsyntaxhighlight lang="nim">block outer:
for i in 0..1000:
for j in 0..1000:
if i + j == 3:
break outer</langsyntaxhighlight>
 
===Try-Except-Finally===
<langsyntaxhighlight lang="nim">var f = open "input.txt"
try:
var s = readLine f
Line 1,470 ⟶ 1,642:
echo "An error occurred!"
finally:
close f</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,476 ⟶ 1,648:
An OCaml user can simulate flow control using exceptions:
 
<langsyntaxhighlight lang="ocaml">exception Found of int
 
let () =
Line 1,485 ⟶ 1,657:
print_endline "nothing found"
with Found res ->
Printf.printf "found %d\n" res</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,492 ⟶ 1,664:
 
break allows to break the current loop :
<syntaxhighlight lang Oforth="oforth">break</langsyntaxhighlight>
 
continue allows to immediately start a new iteration :
<syntaxhighlight lang Oforth="oforth">continue</langsyntaxhighlight>
 
perform is a method that transfer execution to the runnable on top of the stack, then returns :
<syntaxhighlight lang Oforth="oforth">perform</langsyntaxhighlight>
 
=={{header|Oz}}==
Line 1,504 ⟶ 1,676:
 
The <code>case</code> statement can be used for [[Pattern Matching]], but also like a switch statement in C:
<langsyntaxhighlight lang="oz">case {OS.rand} mod 3
of 0 then {Foo}
[] 1 then {Bar}
[] 2 then {Buzz}
end</langsyntaxhighlight>
 
The Lisp-influenced [http://www.mozart-oz.org/home/doc/loop/index.html for-loop] is very powerful and convenient to use.
Line 1,524 ⟶ 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.
 
<langsyntaxhighlight lang="oz">declare
proc {Stupid X}
choice
Line 1,538 ⟶ 1,710:
end
in
{Show {SearchOne Stupid}}</langsyntaxhighlight>
 
{{out}}
Line 1,553 ⟶ 1,725:
=={{header|Pascal}}==
===goto===
<langsyntaxhighlight lang="pascal">label
jumpto;
begin
Line 1,562 ⟶ 1,734:
goto jumpto;
...
end;</langsyntaxhighlight>
 
===exception===
<langsyntaxhighlight lang="pascal">try
Z := DoDiv (X,Y);
except
on EDivException do Z := 0;
end;</langsyntaxhighlight>
 
===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.
<syntaxhighlight lang ="pascal">procedure halt(errnum: Byte);</langsyntaxhighlight>
 
===Exit===
Line 1,581 ⟶ 1,753:
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.
<langsyntaxhighlight lang="pascal">procedure exit(const X: TAnyType)</langsyntaxhighlight>
 
Calls of functions/procedures as well as breaks and continues in loops are described in the corresponding tasks.
Line 1,591 ⟶ 1,763:
Goto is typically looked down upon by most Perl programmers
 
<langsyntaxhighlight lang="perl">FORK:
# some code
goto FORK;</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,599 ⟶ 1,771:
===goto===
In 0.8.4+ Phix finally has a goto statement:
<!--<langsyntaxhighlight Phixlang="phix">-->
<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;">procedure</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
Line 1,608 ⟶ 1,780:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">p</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
Imposing a self-policed rule that all jumps must be forward (or equivalently all backward, but never mixed) is recommended.
 
Line 1,624 ⟶ 1,796:
 
Previous versions had no hll goto statement, however the following work around was (and still is) available:
<langsyntaxhighlight Phixlang="phix">without js
#ilASM{ jmp :label }
...
#ilASM{ ::label }</langsyntaxhighlight>
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.
Line 1,636 ⟶ 1,808:
 
It is also possible to declare global labels, which are superficially similar:
<langsyntaxhighlight Phixlang="phix">without js
#ilASM{ call :%label }
...
Line 1,642 ⟶ 1,814:
:%label
ret
::skip }</langsyntaxhighlight>
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
Line 1,659 ⟶ 1,831:
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:
<!--<langsyntaxhighlight Phixlang="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>
Line 1,671 ⟶ 1,843:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
 
===exit===
causes immediate termination of the immediately surrounding for or while loop, with control passing to the first statement after the loop, eg:
<!--<langsyntaxhighlight Phixlang="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>
Line 1,683 ⟶ 1,855:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
 
===break===
Line 1,708 ⟶ 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).
 
<langsyntaxhighlight lang="php"><?php
goto a;
echo 'Foo';
Line 1,714 ⟶ 1,886:
a:
echo 'Bar';
?></langsyntaxhighlight>
{{out}}
<pre>Bar</pre>
Line 1,764 ⟶ 1,936:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
LEAVE
The LEAVE statement terminates execution of a loop.
Line 1,794 ⟶ 1,966:
labelled statements. (This form is superseded by SELECT, above.)
[GO TO can also be spelled as GOTO].
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 1,801 ⟶ 1,973:
quitloop with argument exits from nested loops:
 
<langsyntaxhighlight lang="pop11">while condition1 do
while condition2 do
if condition3 then
Line 1,807 ⟶ 1,979:
endif;
endwhile;
endwhile;</langsyntaxhighlight>
 
above quitloop(2) exits from both loops.
Line 1,816 ⟶ 1,988:
nested loops:
 
<langsyntaxhighlight lang="pop11">while condition1 do
while condition2 do
if condition3 then
Line 1,823 ⟶ 1,995:
endwhile;
endwhile;
l:;</langsyntaxhighlight>
 
Another use is to implement finite state machines:
 
<langsyntaxhighlight lang="pop11">state1:
DO_SOMETHING();
if condition1 then
Line 1,842 ⟶ 2,014:
...
stateN:
....</langsyntaxhighlight>
 
Pop11 goto is a nonlocal one, so "jump out" from a chain of procedure calls:
 
<langsyntaxhighlight lang="pop11">define outer();
define inner(n);
if n = 0 then
Line 1,855 ⟶ 2,027:
inner(5);
final:;
enddefine;</langsyntaxhighlight>
 
This is useful to exit early from successful recursive search, and for exception handling.
Line 1,863 ⟶ 2,035:
go_on is a multiway jump
 
<langsyntaxhighlight lang="pop11">go_on expression to lab1, lab2, ..., labN else elselab ;</langsyntaxhighlight>
 
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,882 ⟶ 2,054:
it is just:
 
<syntaxhighlight lang ="pop11">return;</langsyntaxhighlight>
 
but it is also possible to specify one or more return values:
 
<langsyntaxhighlight lang="pop11">return(val1, val2, val3);</langsyntaxhighlight>
 
===chain===
Line 1,892 ⟶ 2,064:
chain has effect of "tail call" but is not necessarily in tail position. More precisely inside proc1.
 
<langsyntaxhighlight lang="pop11">chain proc2(x1, x2, x3);</langsyntaxhighlight>
 
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,901 ⟶ 2,073:
===Goto===
Transfers control to the label referenced. It is not a safe way to exit loops.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
top:
i = i + 1
Line 1,912 ⟶ 2,084:
Input()
CloseConsole()
EndIf </langsyntaxhighlight>
===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.
<langsyntaxhighlight PureBasiclang="purebasic">X=1: Y=2
Gosub Calc
;X will now equal 7
Line 1,923 ⟶ 2,095:
Calc:
X+3*Y
Return ; Returns to the point in the code where the Gosub jumped from</langsyntaxhighlight>
===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.
<langsyntaxhighlight PureBasiclang="purebasic">Gosub MySub
 
Lable2:
Line 1,937 ⟶ 2,109:
Goto Lable2
EndIf
Return</langsyntaxhighlight>
 
===OnErrorGoto===
This will transferee the program execution to the defined label if an error accrue.
<langsyntaxhighlight PureBasiclang="purebasic">OnErrorGoto(?MyExitHandler)
 
X=1: Y=0
Line 1,951 ⟶ 2,123:
MyExitHandler:
MessageRequester("Error", ErrorMessage())
End</langsyntaxhighlight>
===OnErrorCall===
Similar to OnErrorGoto() but procedural instead.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure MyErrorHandler()
;All open files etc can be closed here
MessageRequester("Error", ErrorMessage())
Line 1,963 ⟶ 2,135:
X=1: Y=0
Z= X/Y
;This line should never be reached</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="python"># Search for an odd factor of a using brute force:
for i in range(n):
if (n%2) == 0:
Line 1,977 ⟶ 2,149:
else:
result = None
print "No odd factors found"</langsyntaxhighlight>
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,990 ⟶ 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:
 
<syntaxhighlight lang ="python">class MyException(Exception): pass</langsyntaxhighlight>
 
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,998 ⟶ 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:
 
<langsyntaxhighlight lang="python">class MyVirtual(object):
def __init__(self):
raise NotImplementedError</langsyntaxhighlight>
 
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 2,006 ⟶ 2,178:
 
'''Case 1 - Try, Except'''
<langsyntaxhighlight lang="python">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"</langsyntaxhighlight>
 
'''Case 2 - Try, Except'''
<langsyntaxhighlight lang="python">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!"</langsyntaxhighlight>
 
'''Case 3 - Try, Except, Finally'''
<langsyntaxhighlight lang="python">try:
temp = 0/0
except:
Line 2,032 ⟶ 2,204:
# Output :
# An error occurred
# End of 'try' block...</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="python">try:
try:
pass
Line 2,044 ⟶ 2,216:
except SomeOtherException:
finally:
do_some_cleanup() # run in any case, whether any exceptions were thrown or not</langsyntaxhighlight>
 
'''Case 4 - Try, Except, Else'''
<langsyntaxhighlight lang="python">try:
temp = 1/1 # not a division by zero error
except ZeroDivisionError: # so... it is not caught
Line 2,055 ⟶ 2,227:
print "No apparent error occurred."
# Output :
# No apparent error occurred.</langsyntaxhighlight>
 
'''Case 5 - Try, Except, break, continue'''
<langsyntaxhighlight lang="python">i = 0
while 1: # infinite loop
try:
Line 2,077 ⟶ 2,249:
# Output :
# You've divided by zero. Decrementing i and continuing...
# Imaginary Number! Breaking out of loop</langsyntaxhighlight>
 
'''Case 6 - Creating your own custom exceptions, raise'''
<langsyntaxhighlight lang="python"># Let's call our custom error "StupidError"; it inherits from the Exception class
 
class StupidError(Exception): pass
Line 2,092 ⟶ 2,264:
 
# Output :
# Something stupid occurred: Segfault</langsyntaxhighlight>
 
===continue, else in "for" loop===
<langsyntaxhighlight lang="python"> i = 101
for i in range(4): # loop 4 times
print "I will always be seen."
Line 2,114 ⟶ 2,286:
if(__name__ == "__main__"):
main()</langsyntaxhighlight>
 
===The "with" statement===
Line 2,120 ⟶ 2,292:
See [[http://www.python.org/peps/pep-0343.html PEP 0343, The "with" statement]]
 
<langsyntaxhighlight lang="python">class Quitting(Exception): pass
max = 10
with open("some_file") as myfile:
Line 2,128 ⟶ 2,300:
if exit_counter > max:
raise Quitting
print line,</langsyntaxhighlight>
 
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,144 ⟶ 2,316:
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}}==
Line 2,152 ⟶ 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:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,173 ⟶ 2,425:
(return %eax))
(main))
</syntaxhighlight>
</lang>
 
=== Exceptions ===
Line 2,179 ⟶ 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:
 
<langsyntaxhighlight lang="racket">
(define (list-product l)
(with-handlers ([void identity])
Line 2,186 ⟶ 2,438:
[(zero? (car l)) (raise 0)]
[else (loop (cdr l) (* r (car l)))]))))
</syntaxhighlight>
</lang>
 
=== Continuations ===
Line 2,204 ⟶ 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]].
===goto===
<syntaxhighlight lang="raku" perl6line>TOWN: goto TOWN;</langsyntaxhighlight>
Labels that have not been defined yet must be enclosed in quotes.
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Flow Control"
URL: http://rosettacode.org/wiki/Flow_Control_Structures
Line 2,275 ⟶ 2,527:
print div 10 2
print div 10 1
print div 10 0</langsyntaxhighlight>
 
 
Line 2,291 ⟶ 2,543:
 
(Also, see '''function invocation''' and '''signal''' statement below.)
<langsyntaxhighlight lang="rexx">call routineName /*no arguments passed to routine.*/
call routineName 50 /*one argument (fifty) passed. */
call routineName 50,60 /*two arguments passed. */
Line 2,301 ⟶ 2,553:
call routineName ,,,,,,,,,,,,,,,,800 /*17 args passed, 16 omitted. */
call date /*looks for DATE internally first*/
call 'DATE' /* " " " BIF | externally*/</langsyntaxhighlight>
real-life example:
<langsyntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
n=4
Line 2,315 ⟶ 2,567:
!=!*j
end /*j*/
return !</langsyntaxhighlight>
 
===case===
Line 2,333 ⟶ 2,585:
 
(Also, see the '''return''' statement below.)
<langsyntaxhighlight lang="rexx">exit
 
exit expression</langsyntaxhighlight>
 
===function invocation===
Line 2,347 ⟶ 2,599:
 
(Also, see the '''call''' statement above.)
<langsyntaxhighlight lang="rexx">numeric digits 1000 /*prepare for some gihugeic numbers.*/
...
n=4
Line 2,358 ⟶ 2,610:
!=!*j
end /*j*/
return !</langsyntaxhighlight>
 
===iterate===
Line 2,364 ⟶ 2,616:
 
(All indentations in REXX are merely cosmetic and are used for readability.}
<langsyntaxhighlight lang="rexx">sum=0
do j=1 to 1000
if j//3==0 | j//7==0 then iterate
Line 2,381 ⟶ 2,633:
end /*m*/
end /*k*/
say 'prod=' prod</langsyntaxhighlight>
 
===go to===
Line 2,388 ⟶ 2,640:
===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.
<langsyntaxhighlight lang="rexx"> do j=1 to 10
say 'j=' j
if j>5 then leave
Line 2,405 ⟶ 2,657:
end /*m*/
end /*k*/
say 'sum=' sum</langsyntaxhighlight>
 
===raising conditions===
Line 2,416 ⟶ 2,668:
 
(Also, see the '''signal''' statement below.)
<langsyntaxhighlight lang="rexx">...
signal on syntax
...
Line 2,447 ⟶ 2,699:
say; say 'error code:' condition('D')
say; say "Moral: don't do that."
exit 13</langsyntaxhighlight>
{{out}}
<pre>
Line 2,480 ⟶ 2,732:
following the instruction/command where the condition was encountered.
<br>A short example:
<langsyntaxhighlight lang="rexx">Say 'Interrupt this program after a short while'
Call on halt
Do i=1 To 10000000
Line 2,486 ⟶ 2,738:
End
halt: Say i j
Return</langsyntaxhighlight>
 
===return===
Line 2,498 ⟶ 2,750:
 
(Also, see the '''exit''' statement above.)
<langsyntaxhighlight lang="rexx">return
 
return expression</langsyntaxhighlight>
 
===select===
The '''select''' statement is used to conditionally test for cases to selectively execute REXX statement(s).
<langsyntaxhighlight lang="rexx">...
prod=1
a=7 /*or somesuch.*/
Line 2,525 ⟶ 2,777:
end /*select*/
 
say 'result for' a op b "=" r</langsyntaxhighlight>
 
===signal===
Line 2,552 ⟶ 2,804:
 
(Also, see '''raising conditions''' above.)
<langsyntaxhighlight lang="rexx">...
signal on error
signal on failure
Line 2,585 ⟶ 2,837:
say; say 'REXX variable:' condition('D')
say; say "Moral: shouldn't do that."
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,606 ⟶ 2,858:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
i = 1
while true
Line 2,613 ⟶ 2,865:
i = i + 1
end
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 2,623 ⟶ 2,875:
=== 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.
<langsyntaxhighlight lang="ruby">begin
# some code that may raise an exception
rescue ExceptionClassA => a
Line 2,635 ⟶ 2,887:
ensure
# execute this code always
end</langsyntaxhighlight>
There is also a rescue modifier (example from the [http://www.pragprog.com/titles/ruby/programming-ruby Pickaxe book]):
<langsyntaxhighlight lang="ruby">values = ["1", "2.3", /pattern/]
result = values.map {|v| Integer(v) rescue Float(v) rescue String(v)}
# => [1, 2.3, "(?-mix:pattern)"]</langsyntaxhighlight>
 
=== 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):
<langsyntaxhighlight lang="ruby">def some_method
# ...
if some_condition
Line 2,659 ⟶ 2,911:
end
 
puts "continuing after catching the throw"</langsyntaxhighlight>
=== yield ===
<code>yield</code> passes control from the currently executing method to its code block.
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">/* GOTO: as in other languages
STOP: to stop current data step */
data _null_;
Line 2,704 ⟶ 2,956:
8 44
;
run;</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import Goto._
import scala.util.continuations._
 
Line 2,733 ⟶ 2,985:
}
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
===goto===
<langsyntaxhighlight lang="ruby">say "Hello"
goto :world
say "Never printed"
@:world
say "World"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,751 ⟶ 3,003:
=== 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,
<langsyntaxhighlight lang="ssem">00101000000000000000000000000000 20 to CI
...
01010000000000000000000000000000 20. 10</langsyntaxhighlight>
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 ===
<tt>100 Add n to CI</tt> increases the number in the CI register by the value stored at address <i>n</i>.
<langsyntaxhighlight lang="ssem">00101000000001000000000000000000 Add 20 to CI
...
01010000000000000000000000000000 20. 10</langsyntaxhighlight>
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,769 ⟶ 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.
 
<langsyntaxhighlight lang="stata">mata
function pythagorean_triple(n) {
for (a=1; a<=n; a++) {
Line 2,784 ⟶ 3,036:
 
pythagorean_triple(1980)
165 900 915</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,792 ⟶ 3,044:
at some future time asynchronously, like this
 
<syntaxhighlight lang ="tcl">after 1000 {myroutine x}</langsyntaxhighlight>
 
which will call "<tt>myroutine</tt>" with parameter "<tt>x</tt>" 1000ms from 'now';
Line 2,799 ⟶ 3,051:
The scheduled task can be removed from the scheduler for example with
 
<syntaxhighlight lang ="tcl">after cancel myroutine</langsyntaxhighlight>
 
(other ways are possible).
Line 2,808 ⟶ 3,060:
whose display is updated once a second:
 
<langsyntaxhighlight lang="tcl">package require Tk
proc update {} {
.clockface configure -text [clock format [clock seconds]]
Line 2,815 ⟶ 3,067:
# now just create the 'clockface' and call ;update' once:
pack [label .clockface]
update</langsyntaxhighlight>
 
=== loop control ===
Line 2,822 ⟶ 3,074:
=== exception ===
Tcl's <code>catch</code> command can be used to provide a basic exception-handling mechanism:
<langsyntaxhighlight lang="tcl">if {[catch { ''... code that might give error ...'' } result]} {
puts "Error was $result"
} else {
''... process $result ...''
}</langsyntaxhighlight>
Tcl 8.6 also has a <tt>try</tt>…<tt>trap</tt>…<tt>finally</tt> structure for more complex exception handling.
<langsyntaxhighlight lang="tcl">try {
# Just a silly example...
set f [open $filename]
Line 2,837 ⟶ 3,089:
} finally {
close $f
}</langsyntaxhighlight>
 
=== 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:
<langsyntaxhighlight lang="tcl">proc forfilelines {linevar filename code} {
upvar $linevar line ; # connect local variable line to caller's variable
set filechan [open $filename]
Line 2,849 ⟶ 3,101:
}
close $filechan
}</langsyntaxhighlight>
Now we can use it to print the length of each line of file "mydata.txt":
<langsyntaxhighlight lang="tcl">forfilelines myline mydata.txt {
puts [string length $myline]
}</langsyntaxhighlight>
 
=={{header|Tiny BASIC}}==
<langsyntaxhighlight lang="tinybasic"> REM TinyBASIC has only two control flow structures: goto and gosub
LET N = 0
10 LET N = N + 1
Line 2,886 ⟶ 3,138:
105 PRINT "55555"
LET N = N + 1
RETURN REM one return can serve several gosubs</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 2,894 ⟶ 3,146:
This skips the line that changes the value of x to 5.
 
<langsyntaxhighlight lang="vbnet"> Sub bar2()
Dim x = 0
GoTo label
Line 2,900 ⟶ 3,152:
label:
Console.WriteLine(x)
End Sub</langsyntaxhighlight>
 
=== On Error Goto ===
 
This brancesbranches in the event of an error. Usually there is an Exit (Sub|Function) to seperateseparate the normal code from the error handling code
 
<langsyntaxhighlight lang="vbnet"> Sub foo()
On Error GoTo label
'do something dangerous
Line 2,912 ⟶ 3,164:
label:
Console.WriteLine("Operation Failed")
End Sub</langsyntaxhighlight>
 
''This style of code is rarely used.''
Line 2,920 ⟶ 3,172:
This performs a sequence of actions. If any action fails, the exception is discarded and next operation is performed.
 
<langsyntaxhighlight lang="vbnet">Sub foo2()
On Error Resume Next
Operation1()
Line 2,926 ⟶ 3,178:
Operation3()
Operation4()
End Sub</langsyntaxhighlight>
 
''This style of code is rarely used.''
Line 2,934 ⟶ 3,186:
This shows the classical and modern syntax for exiting a sub routine early.
 
<langsyntaxhighlight lang="vbnet">Sub Foo1()
If Not WorkNeeded() Then Exit Sub
DoWork()
Line 2,942 ⟶ 3,194:
If Not WorkNeeded() Then Return
DoWork()
End Sub</langsyntaxhighlight>
 
=== Return value / Exit Function ===
Line 2,950 ⟶ 3,202:
This variable is write-only.
 
<langsyntaxhighlight lang="vbnet">Function Foo3()
Foo3 = CalculateValue()
If Not MoreWorkNeeded() Then Exit Function
Line 2,960 ⟶ 3,212:
If Not MoreWorkNeeded() Then Return result
Return CalculateAnotherValue()
End Function</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 2,976 ⟶ 3,228:
 
The following code demonstrates each of the above apart from '''Fiber.suspend''' which simply exits a CLI script.
<langsyntaxhighlight ecmascriptlang="wren">var func = Fn.new { |n|
var i = 1
while (true) {
Line 2,992 ⟶ 3,244:
 
var fiber = Fiber.new {
Fiber.abort("Demo error") // error occcurredoccurred, abort script
}
 
Line 2,998 ⟶ 3,250:
for (n in a) {
func.call(n)
if (n > 2) return // end module and hence the script as itsit's a single module script
var error = fiber.try() // catch any error
System.print("Caught error: " + error)
}</langsyntaxhighlight>
 
{{out}}
Line 3,012 ⟶ 3,264:
</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}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="yabasic">
gosub subrutina
 
Line 3,028 ⟶ 3,299:
return
end
</syntaxhighlight>
</lang>
 
=={{header|Z80 Assembly}}==
Line 3,039 ⟶ 3,310:
===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.
<langsyntaxhighlight lang="z80">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.
Line 3,045 ⟶ 3,316:
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.</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="z80">foo:
push af
bar:
Line 3,060 ⟶ 3,331:
exit:
pop af
ret</langsyntaxhighlight>
 
===DJNZ===
Line 3,067 ⟶ 3,338:
(Game Boy doesn't have this instruction - you'll have to use a combination of <code>DEC B</code> and <code>JR NZ</code>)
 
<langsyntaxhighlight lang="z80">loop:
;your code goes here
DJNZ loop</langsyntaxhighlight>
 
===Block Instructions===
Line 3,077 ⟶ 3,348:
 
Essentially it's equivalent to the code below, except in the real <code>LDIR</code> the accumulator isn't actually altered in any way.
<langsyntaxhighlight lang="z80">_LDIR:
ld a,(hl)
ld (de),a
Line 3,085 ⟶ 3,356:
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.</langsyntaxhighlight>
 
There are several others that work in a similar fashion, such as:
Line 3,097 ⟶ 3,368:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
zkl has state machines for functional style stream processing. There are some special values that machines can return for flow control:
<pre>
Line 3,113 ⟶ 3,384:
</pre>
As an example, decode URL strings:
<langsyntaxhighlight lang="zkl">urlText.pump(String,
fcn(c){ if(c=="%")return(Void.Read,2); return(Void.Skip,c) },
fcn(_,b,c){(b+c).toInt(16).toChar()})</langsyntaxhighlight>
has two machines. The second machine only runs if "%" is seen.
<langsyntaxhighlight lang="zkl">urlText:="http%3A%2F%2Ffoo.com%2Fbar";
urlText.pump(...).println();</langsyntaxhighlight>
{{out}}<pre>http://foo.com/bar</pre>
5

edits