Jump anywhere: Difference between revisions

m
→‎{{header|TXR}}: Fixed unfinished </code> tag
m (→‎{{header|TXR}}: Fixed unfinished </code> tag)
 
(34 intermediate revisions by 16 users not shown)
Line 23:
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
<br><br>
 
=={{header|360 Assembly}}==
The unconditionnal branch instruction <b>B</b> is the jump anywhere of the S/360 assembler.
<syntaxhighlight lang="360asm"> ...
B ANYWHERE branch
...
ANYWHERE EQU * label
...</syntaxhighlight>
 
=={{header|6502 Assembly}}==
Line 29 ⟶ 37:
===Direct Jump===
This is strictly a one-way trip, just like GOTO in BASIC. The program counter will be set to the specified address or label. This technique is limited to constants. In other words, a direct jump cannot be altered at runtime (self-modifying code notwithstanding)
<langsyntaxhighlight lang="6502asm">JMP PrintChar ; jump to the label "PrintChar" where a routine to print a letter to the screen is located.</langsyntaxhighlight>
 
===Indirect Jump===
This method is a form of the "computed GOTO" and lets you jump to an address stored in a pair of memory addresses. The least effective way to do this is as follows:
<langsyntaxhighlight lang="6502asm">lda #<PrintChar ;load into A the low byte of the address that PrintChar references.
sta $00
lda #>PrintChar ;load into A the high byte of the address that PrintChar references.
sta $01 ;these need to be stored low then high because the 6502 is a little-endian cpu
JMP ($00) ;dereferences to JMP PrintChar</langsyntaxhighlight>
 
The above example is just the same as a direct jump but more complicated for no added benefit. To actually use an indirect jump correctly, the input needs to be variable. Here's one way to do that:
 
<langsyntaxhighlight lang="6502asm">JumpTable_Lo: db <PrintChar, <WaitChar, <ReadKeys, <MoveMouse ;each is the low byte of a memory address
JumpTable_Hi: db >PrintChar, >WaitChar, >ReadKeys, >MoveMouse ;each is the high byte of a memory address
 
Line 48 ⟶ 56:
lda JumpTable_Hi,x
sta $11
JMP ($0010)</langsyntaxhighlight>
 
Depending on the value of x, you will be taken to a different procedure. Once again, this is a one-way jump and you can't return.
Line 54 ⟶ 62:
Another way to do this is with a "jump block."
 
<langsyntaxhighlight lang="6502asm">.org $8000
JMP PrintChar
JMP WaitChar
JMP ReadKeys
JMP MoveMouse
</syntaxhighlight>
</lang>
 
Each jump instruction on the 6502 takes up 3 bytes: one for the JMP command itself, and two for the destination. Knowing this, we can use a variable that is a multiple of 3 to take us to the desired location. Let's pretend X is such a variable, and this routine lets us JMP to the "next" routine.
<langsyntaxhighlight lang="6502asm">lda $80
sta $21
txa
Line 68 ⟶ 76:
adc #$03
sta $20
JMP ($0020)</langsyntaxhighlight>
 
If X was 0, the JMP takes us to WaitChar.
Line 80 ⟶ 88:
The 65c02, which was used in the Apple II and the Atari Lynx, can perform an indirect jump offset by X. This can be used to perform the above technique with much less setup.
 
<langsyntaxhighlight lang="6502asm">JumpTable:
word PrintChar
word PrintString
Line 86 ⟶ 94:
 
ldx #$02
JMP (JumpTable,x) ;dereferences to JMP PrintString</langsyntaxhighlight>
 
Your index needs to be a multiple of 2 for this to work, most of the time you'll use <code>ASL A</code> then <code>TAX</code>to double your index prior to performing the indirect jump.
Line 94 ⟶ 102:
 
Unfortunately, you cannot simply replace "JMP" in the above example with "JSR" as that is not a valid command. What you have to do instead is a bit trickier. One way to accomplish this is with a "Return Table." Let's rewrite JumpTable_Lo and JumpTable_Hi in that format.
<langsyntaxhighlight lang="6502asm">ReturnTable: dw PrintChar-1,WaitChar-1,ReadKeys-1,MoveMouse-1</langsyntaxhighlight>
 
For this example, assume that all of those labels are subroutines that end in an RTS instruction. This method won't work otherwise. Once your return table is defined, you need some sort of variable that allows you to index into that table (i.e. select a subroutine to use).
We'll assume for the code below that the accumulator contains such a variable right now.
 
<langsyntaxhighlight lang="6502asm">
;execution is currently here
JSR UseReturnTable ;the address just after this label is pushed onto the stack.
Line 114 ⟶ 122:
RTS ;this "RTS" actually takes you to the desired subroutine.
;The top two bytes of the stack are popped, the low byte is incremented by 1,
;and this value becomes the new program counter.</langsyntaxhighlight>
 
Now all of that was a bit confusing wasn't it? Essentially this "abuses" the following concepts:
Line 129 ⟶ 137:
 
This is all very complicated, and luckily if you're programming for the 16-bit 65816 you don't have to do this. The 65816 (which was used in the Super Nintendo) has a special command just for doing this. <code>JSR ($####,x)</code> can be used for selecting from a list of functions to call.
 
===Long Jump===
This is only available on the 65816 thanks to its extended 24-bit address space. A standard <code>JMP</code> on the 65816 is confined to <code>$nn0000-$nnFFFF</code>. To break free of this limitation, you'll need to use <code>JML $xxxxxx</code> to go to a different bank. <code>JSL $xxxxxx</code> can call a subroutine in a different bank, and you'll need to use <code>RTL</code> to safely return from a <code>JSL</code>.
 
=={{header|68000 Assembly}}==
Line 136 ⟶ 147:
In addition, for nearby subroutines, <code>BSR</code> can be used in place of <code>JSR</code> to save data. There is also <code>BRA</code> (branch always) for unconditional local jumping, which the original 6502 didn't have.
 
<langsyntaxhighlight lang="68000devpac">bra foo
nop ;execution will never reach here
foo:
Line 143 ⟶ 154:
BGE D1_Is_Greater_Than_Or_Equal_To_D0
; your code for what happens when D1 is less than D0 goes here
D1_Is_Greater_Than_Or_Equal_To_D0:</langsyntaxhighlight>
 
===Absolute Jumps===
The 68000 has <code>JMP</code> and <code>JSR</code> for absolute jumping and function calls, respectively. When you <code>JSR</code>, the next <code>RTS</code> you encounter will return the program counter to just after the <code>JSR</code> statement you came from, provided that the return address is still on top of the stack when the <code>RTS</code> is executed. The CPU assumes that the top 4 bytes of the stack are the correct return address, and has no way of knowing if it's wrong. A sequence like this will likely result in a crash or otherwise undefined behavior:
<langsyntaxhighlight lang="68000devpac">JSR foo:
 
; this is somewhere far away from the JSR above
foo:
MOVE.L D0,(SP)+
RTS ;the CPU will "return" to the value that was in D0, not the actual return address.</langsyntaxhighlight>
 
This can be abused for our benefit, allowing the programmer to select a subroutine from a list of functions. This trick goes by many names, some of the more common ones are "RTS Trick" or "Ret-poline" (a portmanteau of x86's <code>RET</code> and trampoline. <code>RET</code> is called <code>RTS</code> on the 6502 and 68000)
 
<langsyntaxhighlight lang="68000devpac">;For this example, we want to execute "ReadJoystick"
MOVE.W D0,#1
JSR Retpoline
Line 172 ⟶ 183:
 
SubroutineTable:
DC.L MoveMouse, DC.L ReadJoystick, DC.L ReadKeyboard, DC.L PrintString</langsyntaxhighlight>
 
===Indirect Jumps===
Line 181 ⟶ 192:
 
<code>JCXZ</code> will jump only if the <code>CX</code> register equals 0. This is useful for skipping a loop if <code>CX</code> (the loop counter) is already zero.
<langsyntaxhighlight lang="asm">JCXZ bar
foo:
LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo
bar:</langsyntaxhighlight>
 
<code>LOOP label</code> is the equivalent of <code>DEC CX JNZ label</code> and, as the name implies, is used for looping. You might have heard that <code>DEC CX JNZ label</code> should always be used over <code>LOOP label</code> for better performance. This is only true on later x86-based CPUs - the reasons for <code>LOOP</code>'s poor performance weren't present on the 8086, and as such it's better to use there.
Line 190 ⟶ 201:
 
Although <code>JMP</code> was referred to as "unconditional" before, it does ''not'' have access to the entire address space of the CPU, unlike the 6502, Z80, and 68000. The 8086 uses a segmented memory model, where it uses 20-bit addresses despite being a 16-bit CPU. The other 4 bits are the "segment," and a <code>JMP</code> or <code>CALL</code> cannot exit that segment.
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program julpanaywhere64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessResult: .asciz "loop indice : "
szMessage1: .asciz "Display to routine call by register\n"
szMessage2: .asciz "Equal to zero.\n"
szMessage3: .asciz "Not equal to zero.\n"
szMessage4: .asciz "loop start\n"
szMessage5: .asciz "No executed.\n"
szMessResult1: .asciz ","
szMessResult2: .asciz "]\n"
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
 
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess // branch and link to routine
// return here after routine execution
b label1 // branch unconditional to label
ldr x0,qAdrszMessage5 // this instruction is never executed
bl affichageMess // and this
label1:
ldr x0,qAdrszMessage4
bl affichageMess
mov x20,0
1:
mov x0,x20
ldr x1,qAdrsZoneConv
bl conversion10 // decimal conversion
strb wzr,[x1,x0]
mov x0,#3 // number string to display
ldr x1,qAdrszMessResult
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszCarriageReturn
bl displayStrings // display message
add x20,x20,1 // increment indice
cmp x20,5
blt 1b // branch for loop if lower
mov x0,0
cbz x0,2f // jump to label 2 if x0 = 0
2:
adr x1,affichageMess // load routine address in register
ldr x0,qAdrszMessage1
blr x1
mov x4,4
cmp x4,10
bgt 3f // branch if higter
mov x0,x4
3:
mov x0,0b100 // 1 -> bit 2
tbz x0,2,labzero // if bit 2 equal 0 jump to label
ldr x0,qAdrszMessage3 // bit 2 <> 0
bl affichageMess
b endtest // jump end if else
labzero: // display if bit equal to 0
ldr x0,qAdrszMessage2
bl affichageMess
endtest:
mov x0,0b000 // 0 -> bit 2
tbnz x0,2,4f // if bit 2 <> 0 jump to label
ldr x0,qAdrszMessage2 // bit 2 = 0
bl affichageMess
b 5f // jump end test
4: // display if bit equal to 1
ldr x0,qAdrszMessage3
bl affichageMess
5:
 
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
qAdrszMessage1: .quad szMessage1
qAdrszMessage2: .quad szMessage2
qAdrszMessage3: .quad szMessage3
qAdrszMessage4: .quad szMessage4
qAdrszMessage5: .quad szMessage5
qAdrszMessStart: .quad szMessStart
 
/***************************************************/
/* display multi strings */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: // INFO: displayStrings
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
add fp,sp,#48 // save paraméters address (6 registers saved * 8 bytes)
mov x4,x0 // save strings number
cmp x4,#0 // 0 string -> end
ble 100f // branch to equal or smaller
mov x0,x1 // string 1
bl affichageMess
cmp x4,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x4,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x4,#3
ble 100f
mov x3,#3
sub x2,x4,#4
1: // loop extract address string on stack
ldr x0,[fp,x2,lsl #3]
bl affichageMess
subs x2,x2,#1
bge 1b
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret // return to addtress stored in lr
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
loop start
loop indice : 0
loop indice : 1
loop indice : 2
loop indice : 3
loop indice : 4
Display to routine call by register
Not equal to zero.
Equal to zero.
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">
procedure Goto_Test is
begin
Line 242 ⟶ 425:
end Goto_Test;
 
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
Line 261 ⟶ 444:
ARM is very unique in that the program counter can be directly loaded as well as influenced by branching. You need to be very careful when doing this, because loading a value into <code>PC</code> that isn't a multiple of 4 will crash the CPU.
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly">MOV PC,R0 ;loads the program counter with the value in R0. (Any register can be used for this)
LDR PC,[R0] ;loads the program counter with the 32-bit value at the memory location specified by R0</langsyntaxhighlight>
 
This sequence of commands can store registers onto the stack, retrieve them, and return all at once. For this to work properly the only difference in the choice of registers can be that you push <code>LR</code> and pop <code>PC</code>.
<langsyntaxhighlight ARMlang="arm Assemblyassembly">PUSH {R0-R12,LR}
POP {R0-R12,PC}</langsyntaxhighlight>
 
If you don't have access to unified syntax, the above will only work in THUMB mode. For 32-bit ARM, you may have to use
<langsyntaxhighlight ARMlang="arm Assemblyassembly">STMFD sp!,{r0-r12,lr}
LDMFD sp!,{r0-r12,pc}</langsyntaxhighlight>
 
=={{header|Arturo}}==
Line 279 ⟶ 462:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="ahk">; Define a function.
function()
{
Line 315 ⟶ 498:
Suspended
 
*/</langsyntaxhighlight>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="basic">10 GOTO 100: REM jump to a specific line
20 RUN 200: REM start the program running from a specific line</langsyntaxhighlight>
 
Some versions of basic allow line labels to be used. Here we jump to a label:
{{works with|BaCon}}
{{works with|QuickBASIC}}
<syntaxhighlight lang ="qbasic">GOTO mylabel</langsyntaxhighlight>
==={{header|Applesoft BASIC}}===
caveat: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html
<langsyntaxhighlight ApplesoftBASIClang="applesoftbasic"> 0 REM GOTO
100 GOTO 110 : REM JUMP TO A SPECIFIC LINE
110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE
Line 348 ⟶ 531:
280 STOP : REM BREAK THE PROGRAM
290 END : REM END THE PROGRAM
300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0</langsyntaxhighlight>
<langsyntaxhighlight ApplesoftBASIClang="applesoftbasic">CONT : REM CONTINUE, JUMP BACK TO WHERE THE PROGRAM STOPPED</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<lang IS-BASIC>10 GOTO 100 ! jump to a specific line
20 RUN 200 ! start the program running from a specific line</lang>
 
==={{header|Run BASIC}}===
<lang runbasic>for i = 1 to 10
if i = 5 then goto [label5]
next i
end
 
[label5]
print i
while i < 10
if i = 6 then goto [label6]
i = i + 1
wend
end
 
[label6]
print i
if i = 6 then goto [finish]
print "Why am I here"
 
[finish]
print "done"</lang>
 
==={{header|BASIC256}}===
BASIC256 supports both <code>goto</code> and <code>gosub</code>.
{{works with|QBasic}}
{{works with|Yabasic}}
<langsyntaxhighlight lang="freebasic">print "First line."
gosub sub1
print "Fifth line."
Line 402 ⟶ 559:
Finished:
print "... with goto and gosub, thankfully."
end</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FutureBasic.</pre>
 
==={{header|Chipmunk Basic}}===
Chipmunk Basic supports both <code>goto</code> and <code>gosub</code>.
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS
110 PRINT "First line."
120 GOSUB sub1
130 PRINT "Fifth line."
140 GOTO Ending
150 sub1:
160 PRINT "Second line."
170 GOSUB sub2
180 PRINT "Fourth line."
190 RETURN
200 Ending:
210 PRINT "We're just about done..."
220 GOTO Finished
230 sub2:
240 PRINT "Third line."
250 RETURN
260 Finished:
270 PRINT "... with goto and gosub, thankfully."
280 END</syntaxhighlight>
{{out}}
<pre>Same as FutureBasic entry.</pre>
 
==={{header|GW-BASIC}}===
GW-BASIC supports both <code>goto</code> and <code>gosub</code>.
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|Minimal BASIC}}
{{works with|MSX BASIC|any}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|Quite BASIC}}
<syntaxhighlight lang="qbasic">100 PRINT "First line."
110 GOSUB 140
120 PRINT "Fifth line."
130 GOTO 190
140 REM sub1:
150 PRINT "Second line."
160 GOSUB 220
170 PRINT "Fourth line."
180 RETURN
190 REM Ending:
200 PRINT "We're just about done..."
210 GOTO 250
220 REM sub2:
230 PRINT "Third line."
240 RETURN
250 REM Finished:
260 PRINT "... with goto and gosub, thankfully."
270 END</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">10 GOTO 100 ! jump to a specific line
20 RUN 200 ! start the program running from a specific line</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|Quite BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 1 to 10
if i = 5 then goto [label5]
next i
end
 
[label5]
print i
while i < 10
if i = 6 then goto [label6]
i = i + 1
wend
end
 
[label6]
print i
if i = 6 then goto [finish]
print "Why am I here"
 
[finish]
print "done"</syntaxhighlight>
 
==={{header|True BASIC}}===
True BASIC supports both <code>goto</code> and <code>gosub</code>.
<syntaxhighlight lang="qbasic">100 ! Jump anywhere
110 CLEAR
120 PRINT "First line."
130 GOSUB 160
140 PRINT "Fifth line."
150 GOTO 210
160 ! sub1:
170 PRINT "Second line."
180 GOSUB 250
190 PRINT "Fourth line."
200 RETURN
210 ! Ending:
220 PRINT "We're just about done..."
230 GOTO 270
240 ! sub2:
250 PRINT "Third line."
260 RETURN
270 ! Finished:
280 PRINT "... with goto and gosub, thankfully."
290 END</syntaxhighlight>
{{out}}
<pre>Same as FutureBasic entry.</pre>
 
==={{Header|Tiny BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
=={{header|BQN}}==
Jumping anywhere (akin to APL's `→`) is not possible in BQN, and BQN does not have labels either.
The main forms of jumping are within blocks.
=== Block predicates ===
These constitute conditional jumps. If the value is 0, the section following it is skipped.
<syntaxhighlight lang="bqn"> { 0 ? "Will not execute"; "Will execute" }
"Will execute"</syntaxhighlight>
=== Function calls ===
You can call a function from a block, temporarily jumping over to the function's body, and coming back.
<syntaxhighlight lang="bqn"> F←{𝕩⊣•Out"In Second"}
{
•Out "First"
F@
•Out "Last"
}</syntaxhighlight>
 
<syntaxhighlight lang="bqn"> First
In Second
Last</syntaxhighlight>
 
=={{header|C}}==
C has <code>goto LABEL</code> keyword.
<langsyntaxhighlight lang="c"> if (x > 0) goto positive;
else goto negative;
 
Line 418 ⟶ 713:
 
both:
...</langsyntaxhighlight>
The label must be literal, not computed at run time. This won't work:
<langsyntaxhighlight lang="c">goto (x > 0 ? positive : negative);</langsyntaxhighlight>
<!-- Except if you're using GCC extensions, when you can do something that's very similar to that. Scary stuff! -->
You can <code>goto</code> ''almost'' anywhere inside the same function, but can't go across function boundaries. It's sometimes used to break out of nested loops:<langsyntaxhighlight lang="c">for (i = 0; ...) {
for (j = 0; ...) {
if (condition_met) goto finish;
}
}</langsyntaxhighlight>although you can (not that you ''should'') jump into a loop, too:<langsyntaxhighlight lang="c"> goto danger;
for (i = 0; i < 10; i++) {
danger: /* unless you jumped here with i set to a proper value */
printf("%d\n", i);
}</langsyntaxhighlight>
For unwrapping call stack and go back up to a caller, see [[Exceptions#C|longjmp example]]; more powerful, but more expensive and complicated, is POSIX [[Exceptions/Catch an exception thrown in a nested call#C|ucontext]].
The best application for goto is error handling, this simplifies the resource clean up of a large function.
Line 437 ⟶ 732:
 
 
<syntaxhighlight lang="c">
<lang c>
char *str;
int *array;
Line 463 ⟶ 758:
...// read in the csv file and convert to integers
 
</syntaxhighlight>
</lang>
 
 
<syntaxhighlight lang="c">
<lang c>
char *str;
int *array;
Line 492 ⟶ 787:
exit:
return;
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
Like C, C# also has a <code>goto LABEL</code> keyword. This section is partly copied from the section on C, since both languages share common syntax.
<langsyntaxhighlight lang="csharp">if (x > 0) goto positive;
else goto negative;
 
Line 506 ⟶ 801:
 
both:
...</langsyntaxhighlight>
The label must be literal, not computed at run time. This won't work:
<langsyntaxhighlight lang="csharp">goto (x > 0 ? positive : negative);</langsyntaxhighlight>
 
You can <code>goto</code> ''almost'' anywhere inside the same method, but can't go across method boundaries. It's sometimes used to break out of nested loops:
<langsyntaxhighlight lang="csharp">for (i = 0; ...) {
for (j = 0; ...) {
if (condition_met) goto finish;
}
}</langsyntaxhighlight>
The label must be in scope, so you cannot jump into a loop. This will not compile:
<langsyntaxhighlight lang="csharp">goto danger;
for (i = 0; i < 10; i++) {
danger:
Console.WriteLine(i);
}</langsyntaxhighlight>
 
In C#, you can also <code>goto</code> a label from within any section of a try .. catch block. However, it is not permitted to jump out of a finally block.
<langsyntaxhighlight lang="csharp">int i = 0;
tryAgain:
try {
Line 535 ⟶ 830:
finally {
//goto end; //Error
}</langsyntaxhighlight>
 
Another usage of <code>goto</code> is to jump between <code>case</code> labels inside a <code>switch</code> statement:
<langsyntaxhighlight lang="csharp">public int M(int n) {
int result = 0;
switch (n) {
Line 552 ⟶ 847:
}
return result;
}</langsyntaxhighlight>
 
=={{header|C++}}==
Like C, C++ also has a <code>goto LABEL</code> statement which can be used to jump within a function.
 
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
#include <utility>
 
Line 602 ⟶ 897:
cout << "k = " << k << "\n"; // k was never initialized, accessing it is undefined behavior
}</langsyntaxhighlight>
 
{{out}}
Line 616 ⟶ 911:
 
=={{header|COBOL}}==
<langsyntaxhighlight cobollang="cobolfree"> IDENTIFICATION DIVISION.
PROGRAM-ID. JUMPSjumps-PROGRAMprogram.
* Nobody writes like this, of course; but...
 
PROCEDURE DIVISION.
PROCEDURE DIVISION.
 
* You can jump anywhere you like.
start-paragraph.
START-PARAGRAPH.
GO TO ANan-ARBITRARYarbitrary-PARAGRAPHparagraph.
 
YET-ANOTHER-PARAGRAPH.
yet-another-paragraph.
ALTER START-PARAGRAPH TO PROCEED TO A-PARAGRAPH-SOMEWHERE.
ALTER start-paragraph TO PROCEED TO a-paragraph-somewhere.
* That's right, folks: we don't just have GO TOs, we have GO TOs whose
* destinations can be changed at will, from anywhere in the program,
* at run time.
GO TO STARTstart-PARAGRAPHparagraph.
* But bear in mind: once you get there, the GO TO no longer goes to
* where it says it goes to.
 
A-PARAGRAPH-SOMEWHERE.
a-paragraph-somewhere.
DISPLAY 'Never heard of him.'
DISPLAY 'Never heard of him.'
STOP RUN.
STOP RUN.
SOME-OTHER-PARAGRAPH.
 
some-other-paragraph.
* You think that's bad? You ain't seen nothing.
GO TO YETyet-ANOTHERanother-PARAGRAPHparagraph.
 
AN-ARBITRARY-PARAGRAPH.
an-arbitrary-paragraph.
DISPLAY 'Edsger who now?'
DISPLAY 'Edsger who now?'
GO TO SOME-OTHER-PARAGRAPH.</lang>
GO TO some-other-paragraph.
 
END PROGRAM jumps-program.</syntaxhighlight>
{{out}}
<pre>Edsger who now?
Line 646 ⟶ 949:
'''COBOL''' also supports computed go to phrases, given a list of labels (paragraph names) and an integer index into that list.
 
<syntaxhighlight lang="cobolfree"> DATA DIVISION.
<lang COBOL>01 province pic 99 value 2.
WORKING-STORAGE SECTION.
GO TO quebec, ontario, manitoba DEPENDING ON province</lang>
01 province PICTURE IS 99 VALUE IS 2.
 
PROCEDURE DIVISION.
GO TO quebec, ontario, manitoba DEPENDING ON province.
* Jumps to section or paragraph named 'ontario'.</syntaxhighlight>
 
=={{header|Common Lisp}}==
In Common Lisp you can jump anywhere inside a tagbody.
<langsyntaxhighlight lang="lisp">
(tagbody
beginning
Line 665 ⟶ 973:
(sleep 1)
(go middle))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 680 ⟶ 988:
=={{header|Computer/zero Assembly}}==
A <tt>JMP</tt> (jump) instruction can transfer control to any point in memory. Its target can be modified at run time, if required, by using instruction arithmetic:
<langsyntaxhighlight lang="czasm"> LDA goto
SUB somewhere
ADD somewhereElse
STA goto
goto: JMP somewhere</langsyntaxhighlight>
By the time execution reaches the instruction labelled <tt>goto</tt>, that instruction has become <tt>JMP somewhereElse</tt>. (This kind of coding does not, however, necessarily make the flow of control easier to follow.)
 
Line 691 ⟶ 999:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ return ! ignored since we haven't done a gosub yet
$
$ if p1 .eqs. "" then $ goto main
Line 761 ⟶ 1,069:
$ sub4: subroutine
$ exit
$ endsubroutine</langsyntaxhighlight>
{{out}}
<pre>$ @jump_anywhere
Line 862 ⟶ 1,170:
Déjà Vu supports continuations:
 
<langsyntaxhighlight lang="dejavu">example:
!print "First part"
yield
Line 869 ⟶ 1,177:
local :continue example
!print "Interrupted"
continue</langsyntaxhighlight>
{{out}}
<pre>First part
Line 880 ⟶ 1,188:
Every function/procedure must have your own labels, globals labels won't work in local functions.
The label must be literal, not computed at run time.
<syntaxhighlight lang="delphi">
<lang Delphi>
var
x: Integer = 5;
Line 902 ⟶ 1,210:
readln;
end.
</syntaxhighlight>
</lang>
Although you can (not that you should) jump into a loop, too. If you use a loop variable, it will start with its value.
If the loop variable has a value out range loop limits, then you cause a intinity loop.
<syntaxhighlight lang="delphi">
<lang Delphi>
label
inloop, outloop;
Line 924 ⟶ 1,232:
readln;
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 939 ⟶ 1,247:
This won't work.
 
<syntaxhighlight lang="delphi">
<lang Delphi>
label
tryAgain, finished;
Line 957 ⟶ 1,265:
readln;
end.
</syntaxhighlight>
</lang>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|EMal has no goto statement.
|The closes statements are break, continue, return, exit
|and exceptions management.
|^
fun sample = void by block
for int i = 1; i < 10; ++i
if i == 1 do continue end # jumps to next iteration when 'i' equals 1
writeLine("i = " + i)
if i > 4 do break end # exits the loop when 'i' exceeds 4
end
for int j = 1; j < 10; ++j
writeLine("j = " + j)
if j == 3 do return end # returns from the function when 'j' exceeds 3
end
end
sample()
type StateMachine
^|this code shows how to selectevely jump to specific code
|to simulate a state machine as decribed here:
|https://wiki.tcl-lang.org/page/A+tiny+state+machine
|Functions return the next state.
|^
int n = -1
Map stateMachine = int%fun[
0 => int by block
if Runtime.args.length == 1
n = when(n == -1, int!Runtime.args[0], 0)
else
n = ask(int, "hello - how often? ")
end
return when(n == 0, 2, 1)
end,
1 => int by block
if n == 0 do return 0 end
writeLine(n + " Hello")
n--
return 1
end,
2 => int by block
writeLine("Thank you, bye")
return -1
end]
int next = 0
for ever
next = stateMachine[next]()
if next == -1 do break end
end
</syntaxhighlight>
{{out}}
<pre>
emal.exe Org\RosettaCode\JumpAnywhere.emal 2
i = 2
i = 3
i = 4
i = 5
j = 1
j = 2
j = 3
2 Hello
1 Hello
Thank you, bye
</pre>
 
=={{header|Erlang}}==
Jumps are limited to [[Exceptions]].
Line 963 ⟶ 1,337:
=={{header|ERRE}}==
ERRE has a GOTO statement in the form GOTO <label>. <label> is a numercic string and must be declared. ERRE GOTO is local only: you can jump only within the same procedure or within the main program. In the following example there are two errors:
<syntaxhighlight lang="text">
PROGRAM GOTO_ERR
 
Line 983 ⟶ 1,357:
IF J<>0 THEN GOTO 100 END IF
END PROGRAM
</syntaxhighlight>
</lang>
You can't jump from procedure P1 to procedure P2 or from main to procedure P2 (label 99). Jump to label 100 is allowed (within main program).
 
Line 993 ⟶ 1,367:
A continuation is conceptually simple in Factor. It is a tuple consisting of slots for the five stacks that make up the entire execution context: data stack, call stack, retain stack, name stack, and catch stack. To create a continuation from the current execution context, use <code>current-continuation</code>.
 
<langsyntaxhighlight lang="factor">USING: continuations prettyprint ;
 
current-continuation short.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,003 ⟶ 1,377:
Following is a simple example where we reify a continuation before attempting to divide 1 by 0. Note the current execution context (a <code>continuation</code> object) is placed on the top of the data stack inside the <code>callcc0</code> quotation which <code>continue</code> then reifies.
 
<langsyntaxhighlight lang="factor">USING: continuations math prettyprint ;
 
[ 10 2 / . continue 1 0 / . ] callcc0</langsyntaxhighlight>
{{out}}
<pre>
Line 1,012 ⟶ 1,386:
 
We can even reify a continuation while taking an object back with us.
<langsyntaxhighlight lang="factor">USING: continuations kernel math ;
 
[ 10 2 / swap continue-with 1 0 / ] callcc1</langsyntaxhighlight>
 
{{out}}
Line 1,050 ⟶ 1,424:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ this prints five lines containing elements from the two
\ words 'proc1' and 'proc2'. gotos are used here to jump
\ into and out of the two words at various points, as well
Line 1,078 ⟶ 1,452:
 
5 1 proc2
bye</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight lang="forth">line 1 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 2 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 3 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 4 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="forth">\ this is congruent to the previous demonstration, employing
\ a data structure to store goto/jump addresses instead of
\ separate variables, and two additional words 'mark_goto' and
Line 1,117 ⟶ 1,491:
 
: go 5 1 6 goto ; go
bye</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight lang="forth">line 1 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 2 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 3 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 4 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="forth">\ works with ficl, pfe, gforth, bigforth, and vfx.
\ swiftforth may crash, iforth does not function.
 
Line 1,164 ⟶ 1,538:
5 1 go
 
bye</langsyntaxhighlight>
 
Output:
<langsyntaxhighlight lang="forth">iteration 1 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8
iteration 2 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8
iteration 3 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8
iteration 4 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8
iteration 5 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8</langsyntaxhighlight>
 
 
Line 1,177 ⟶ 1,551:
Although Forth was designed to be a structured programming language it is simple to add a generic jump anywhere.
The Forth dictionary of WORDs is essentially a linked list of labels. We can find the execution token for any label in the dictionary with the ['] operator and jump to it with the keyword EXECUTE.
<langsyntaxhighlight lang="forth">: GOTO ['] EXECUTE ;</langsyntaxhighlight>
 
TEST
<langsyntaxhighlight lang="forth">: WORLD ." World!" ;
: HELLO ." Hello" ;
 
GOTO CR GOTO HELLO GOTO SPACE GOTO WORLD
Hello World!</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,226 ⟶ 1,600:
The following program demonstrate the use of the various 'Goto' constructs in the -lang fb dialect only:
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' compiled with -lang fb (the default) and -e switches
Line 1,275 ⟶ 1,649:
Print
Print "Pres any key to quit"
Print</langsyntaxhighlight>
 
{{out}}
Line 1,294 ⟶ 1,668:
 
All that said, don't use spaghetti code -- use functions. You can still by spark plugs for a 1985 Yugo, but why?
<langsyntaxhighlight lang="futurebasic">
window 1
include "ConsoleWindow"
 
print "First line."
Line 1,314 ⟶ 1,688:
"Outa here"
print "... with goto and gosub, thankfully."
 
end
HandleEvents
</lang>
</syntaxhighlight>
Output:
<pre>
Line 1,333 ⟶ 1,708:
 
For example:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,353 ⟶ 1,728:
k++
fmt.Println(k)
}</langsyntaxhighlight>
 
{{out}}
Line 1,369 ⟶ 1,744:
4
</pre>
::<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,403 ⟶ 1,778:
func init() {
fmt.Println("run first")
}</langsyntaxhighlight>
 
=={{header|Harbour}}==
Line 1,414 ⟶ 1,789:
 
First some boilerplate, where we define labels and goto "operator".
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad.Cont
 
data LabelT r m = LabelT (ContT r m ())
Line 1,426 ⟶ 1,801:
 
runProgram :: Monad m => ContT r m r -> m r
runProgram program = runContT program return</langsyntaxhighlight>
 
Here is example of using labels in IO:
<langsyntaxhighlight Haskelllang="haskell">main = runProgram $
do
start <- label
Line 1,437 ⟶ 1,812:
then do lift $ putStrLn "Name can't be empty!"
goto start
else lift $ putStrLn ("Hello, " ++ name)</langsyntaxhighlight>
 
{{Out}}
Line 1,449 ⟶ 1,824:
 
We can build tiny EDSL to get rid of explicit lifting and to add refferences:
<langsyntaxhighlight Haskelllang="haskell">import Data.IORef
 
readInt = lift $ readLn >>= newIORef
get ref = lift $ readIORef ref
set ref expr = lift $ modifyIORef ref (const expr)
output expr = lift $ putStrLn expr</langsyntaxhighlight>
 
and implement famous Euclid's algorithm as an imperative program:
<langsyntaxhighlight Haskelllang="haskell">gcdProg = runProgram $ callCC $ \exit -> -- <--------+
do -- |
start <- label -- <-----+ |
Line 1,475 ⟶ 1,850:
when (n > m) $ set nr (n - m) -- |
when (m > n) $ set mr (m - n) -- |
goto loop -- ---+</langsyntaxhighlight>
 
{{Out}}
Line 1,489 ⟶ 1,864:
In native Haskell such flow jumps are done by function calls:
 
<langsyntaxhighlight Haskelllang="haskell">gcdFProg = start
where
start = do
Line 1,505 ⟶ 1,880:
| n == m = n
| n < m = loop n (m-n)
| n > m = loop (n-m) m</langsyntaxhighlight>
 
Or without explicit recursion and branching:
 
<langsyntaxhighlight Haskelllang="haskell">import Control.Applicative
import Control.Monad.Trans.Maybe
 
Line 1,520 ⟶ 1,895:
process = gcd <$> (lift readLn >>= exitOn 0) <*> lift readLn
 
exitOn n x = if x == n then empty else pure x</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">//'i' does not have goto statements, instead control flow is the only legal way to navigate the program.
concept there() {
print("Hello there")
Line 1,551 ⟶ 1,926:
//Move to the code contained in the 'there' function.
there()
}</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,557 ⟶ 1,932:
 
For example:
<langsyntaxhighlight lang="j">F=: verb define
smoutput 'Now we are in F'
G''
Line 1,570 ⟶ 1,945:
F''
Now we are in F
Now we are in G</langsyntaxhighlight>
 
J also supports jumps to labels within a definition (but makes them a bit tedious to express, which has been rather successful at discouraging their use):
 
<langsyntaxhighlight lang="j">H=: verb define
smoutput 'a'
label_b.
Line 1,591 ⟶ 1,966:
c
g
e</langsyntaxhighlight>
 
=={{header|Java}}==
The closest thing that Java has to a "goto" is labelled loops:
<langsyntaxhighlight lang="java">loop1: while (x != 0) {
loop2: for (int i = 0; i < 10; i++) {
loop3: do {
Line 1,612 ⟶ 1,987:
}
//loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed
}</langsyntaxhighlight>
 
It's frowned upon to use exceptions for non-exceptional paths, so get ready to frown at this fizz-buzz player that makes use of <tt>try/catch/finally</tt> to jump to the right places for printing:
<langsyntaxhighlight lang="java">
public class FizzBuzzThrower {
public static void main( String [] args ) {
Line 1,633 ⟶ 2,008:
}
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 1,641 ⟶ 2,016:
jq supports named labels ("label $NAME") and break statements ("break $NAME"). Usage
follows the pattern:
<langsyntaxhighlight lang="jq">label $out | ... break $out ...</langsyntaxhighlight>
 
When, during program execution, a "break" statement is encountered, the program
Line 1,652 ⟶ 2,027:
Break statements are used to interrupt a generator. For example, to emit
the least positive integer satisfying sin(1/N) == (1/N) using IEEE 64-bit arithmetic:
<langsyntaxhighlight lang="jq">label $out | 1e7 | while(true; .+1) | if (1/.) | . == sin then (., break $out) else empty end</langsyntaxhighlight>
 
Here, the "while" filter is an unbounded generator. The answer is 46530688.
Line 1,660 ⟶ 2,035:
Indeed, a better way to solve the type of problem mentioned above is by using one of the jq-provided control structures.
For example, the above problem can be solved more succinctly and transparently using until/2:
<langsyntaxhighlight lang="jq">1e7 | until(1/. | . == sin; .+1)</langsyntaxhighlight>
 
=={{header|Julia}}==
 
Julia provides the @goto and @label macros for goto within functions but these cannot be used at the global level or to jump from one function to another. The macros can however be used for a typical use of @goto -- jumping out to a specific level from nested loops within a function.
<langsyntaxhighlight lang="julia">
function example()
println("Hello ")
Line 1,673 ⟶ 2,048:
println("world")
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 1,681 ⟶ 2,056:
 
For example:
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 1,696 ⟶ 2,071:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,720 ⟶ 2,095:
 
* Lingo supports "unwinding the call stack" via the abort command that exits the current call stack:
<langsyntaxhighlight lang="lingo">on foo
abort()
end
Line 1,727 ⟶ 2,102:
foo()
put "This will never be printed"
end</langsyntaxhighlight>
 
* Rarely used, but Lingo supports saving a continuation via the play ... play done construct:
<langsyntaxhighlight lang="lingo">on testPlayDone ()
 
-- Start some asynchronous process (like e.g. a HTTP request).
Line 1,741 ⟶ 2,116:
-- The following will be executed only after 'play done' was called in the asynchronous process code
put "Done. The asynchronous process returned the result:" && _global.result
end</langsyntaxhighlight>
 
=={{header|Logtalk}}==
Line 1,748 ⟶ 2,123:
=={{header|Lua}}==
Lua 5.2 introduced a <code>goto</code> statement along with labels. It was somewhat controversially implemented instead of a <code>continue</code> keyword, but it is more flexible and supports other types of jumps as well. <code>goto</code> only supports statically-defined labels.
<langsyntaxhighlight lang="lua">-- Forward jump
goto skip_print
print "won't print"
Line 1,785 ⟶ 2,160:
end
print "not found"
::exit::</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,794 ⟶ 2,169:
After Else and Then we can place number to jump (same as Goto number). Goto can't take variable. We can use On Goto to use an expression to choose label (we can place numbers or named labels)
===Using GOTO and GOSUB===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Alfa {
Line 1,828 ⟶ 2,203:
}
Checkit
</syntaxhighlight>
</lang>
 
===Simulate Run Basic Entry===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LikeRunBasic {
for i = 1 to 10
Line 1,855 ⟶ 2,230:
}
LikeRunBasic
</syntaxhighlight>
</lang>
 
===Simulate Go Entry===
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LikeGo {
\\ simulate Go for
Line 1,941 ⟶ 2,316:
LikeGo_No_Labels
 
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Line 1,950 ⟶ 2,325:
=={{header|MBS}}==
 
<syntaxhighlight lang MBS="mbs">goto mylabel;</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
 
<syntaxhighlight lang="text">БП XX</langsyntaxhighlight>
 
'''XX''' is any address.
Line 1,965 ⟶ 2,340:
* &nbsp; <code>jal 0xNNNNNNNN</code> sets the program counter equal to <code>0xNNNNNNNN</code>, and moves the old program counter plus 8 into register <code>$ra</code>.
* &nbsp; <code>jalr $NN,0xNNNNNNNN</code> sets the program counter equal to <code>0xNNNNNNNN</code> and moves the old program counter plus 8 into register <code>$NN</code>.
 
 
Most of the time you won't be jumping to a specific address. You can place a label before any instruction, and a jump to that label is the same as a jump to the address of that instruction.
 
<syntaxhighlight lang="mips">
j GoHere ;the assembler will convert this label to a constant memory address for us.
 
nop ; branch delay slot. This instruction would get executed DURING the jump.
; But since NOP intentionally does nothing, it's not a problem.
 
GoHere:
addiu $t0,1 ;this instruction is the first one executed after jumping.</syntaxhighlight>
 
 
Branches apply a signed offset to the current program counter. They are limited only by distance; scope does not exist in assembly. Typically you do not have calculate this offset yourself. The assembler will abstract this out of the hardware and let you use a label like you would with a <code>j</code>. The actual offset is calculated during the assembly process, which means you don't have to measure it yourself by counting bytes.
Line 1,973 ⟶ 2,361:
 
Some interpreters will allow you jump between blocks of the same depth. Others will let you leave, but not enter, a block.
<langsyntaxhighlight MUMPSlang="mumps"> ;Go to a label within the program file
Goto Label
;Go to a line below a label
Line 1,989 ⟶ 2,377:
. Goto Out
Out Quit
Goto NoNo+2</langsyntaxhighlight>
 
=={{header|Neko}}==
Line 1,995 ⟶ 2,383:
Neko supports colon terminated labels, and a builtin '''$goto(label)'''. This builtin is special in that the label argument is not dereferenced as a normal Neko expression, but specifically as a label.
 
<langsyntaxhighlight ActionScriptlang="actionscript">$print("start\n")
$goto(skip)
$print("Jumped over")
skip:
$print("end\n")</langsyntaxhighlight>
 
The NekoVM keeps exception and call stacks in sync when jumping across boundaries to code blocks, but may not include some initiating side effects. For instance, jumping past a '''try''' phrase into the middle of the code block (where the try is not evaluated) will not catch the '''catch''' of the try catch pair. There are other cases where '''$goto()''' can cross semantic boundaries; a practice best avoided.
Line 2,005 ⟶ 2,393:
=={{header|Nim}}==
Nim has exceptions and labelled breaks:
<langsyntaxhighlight lang="nim">
block outer:
for i in 0..1000:
for j in 0..1000:
if i + j == 3:
break outer</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,022 ⟶ 2,410:
 
Some portion of code can be restarted (as recursion) and skipped (as continuation).
<langsyntaxhighlight lang="scheme">
; recursion:
(let loop ((n 10))
Line 2,036 ⟶ 2,424:
 
(print "ok.")
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
Line 2,045 ⟶ 2,433:
=={{header|Perl}}==
Perl's <code>goto LABEL</code> and <code>goto EXPR</code> are a little too powerful to be safe. Use only under extreme duress (actually, not even then). <code>goto &SUB</code> is esoteric but much more innocuous and can occasionally be handy.
<langsyntaxhighlight lang="perl">sub outer {
print "In outer, calling inner:\n";
inner();
Line 2,079 ⟶ 2,467:
 
print "\nCalling inner:\n";
inner(); # will die</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 2,085 ⟶ 2,473:
Using this 'baroque' syntax is viewed as an effective means of dissuading novices from adopting goto as a weapon of choice.
Note that pwa/p2js does not support #ilASM{} at all. <!--(notonline)-->
<langsyntaxhighlight Phixlang="phix">#ilASM{ jmp :%somelabel }
...
#ilASM{ :%somelabel }</langsyntaxhighlight>
The above shows a global label, which can only be declared in top-level code, not inside a routine, and can be referenced from anywhere.
 
Local labels are declared with a double colon (::) and referenced with a single colon
<langsyntaxhighlight Phixlang="phix">#ilASM{ jmp :local
...
::local }</langsyntaxhighlight>
They can only be referenced at the top level from within the same #ilASM construct, or anywhere within the routine where they are defined.
Phix also supports anonymous local labels
<langsyntaxhighlight Phixlang="phix">#ilASM{ jmp @f
...
@@:
...
jle @b }</langsyntaxhighlight>
There are also optional (global) labels:
<langsyntaxhighlight Phixlang="phix">#ilASM{ call :!optlbl
[32]
pop eax
Line 2,115 ⟶ 2,503:
push qword[rsp]
[]
ret }</langsyntaxhighlight>
These are obviously more useful when the reference and declaration are in separate files: if the file containing the declaration is not included, the reference quietly resolves to 0.
The above code shows how to duplicate the return address and discard on return, so that execution carries on at the next instruction if the definition is not present.
Line 2,123 ⟶ 2,511:
 
Lastly (for completeness) there are init labels, defined using
<syntaxhighlight lang Phix="phix">#ilASM{ :>init }</langsyntaxhighlight>
These are used by the VM (eg builtins\VM\pStack.e declares :>initStack) to specify initialisation code which must be run at startup. They can also be called like a normal global label.
 
Line 2,134 ⟶ 2,522:
 
There is no 'go' or 'goto' function in PicoLisp, but it can be emulated with normal list processing functions. This allows "jumps" to arbitrary locations within (the same or other) functions. The following example implements a "loop":
<langsyntaxhighlight PicoLisplang="picolisp">(de foo (N)
(prinl "This is 'foo'")
(printsp N)
(or (=0 (dec 'N)) (run (cddr foo))) )</langsyntaxhighlight>
Test:
<pre>: (foo 7)
Line 2,152 ⟶ 2,540:
<br>In structured programming, the only place where a <code>goto</code> can be is inside <code>on</code> units to handle exceptions without recursion.
 
<syntaxhighlight lang ="pli">on conversion goto restart;</langsyntaxhighlight>
 
=={{header|PL/SQL}}==
PL/SQL supports both GOTOs and structured exception handling:
<langsyntaxhighlight PLlang="pl/SQLsql">DECLARE
i number := 5;
divide_by_zero EXCEPTION;
Line 2,181 ⟶ 2,569:
DBMS_OUTPUT.put_line( 'Finally' );
END;
/</langsyntaxhighlight>
{{out}}
<pre>startLoop
Line 2,197 ⟶ 2,585:
current loop. The syntax for a label is as follows (this example shows a
label in a While loop):
<syntaxhighlight lang="powershell">
<lang PowerShell>
:myLabel while (<condition>) { <statement list>}
</syntaxhighlight>
</lang>
The label is a colon followed by a name that you assign. The label must be
the first token in a statement, and it must be followed by the looping
Line 2,213 ⟶ 2,601:
This schematic example has a While statement with a For statement:
<syntaxhighlight lang="powershell">
<lang PowerShell>
:myLabel while (<condition 1>)
{
Line 2,223 ⟶ 2,611:
}
$a = $c # A statement after the labeled While-loop
</syntaxhighlight>
</lang>
 
If condition 2 evaluates to True, the execution of the script skips down
Line 2,231 ⟶ 2,619:
You can nest many labeled loops, as shown in the following schematic
example.
<syntaxhighlight lang="powershell">
<lang PowerShell>
:red while (<condition1>)
{
Line 2,247 ⟶ 2,635:
}
# After "red" loop
</syntaxhighlight>
</lang>
If the $b variable evaluates to True, execution of the script resumes
after the loop that is labeled "red". If the $c variable evaluates to
Line 2,260 ⟶ 2,648:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">OnErrorGoto(?ErrorHandler)
OpenConsole()
Gosub label4
Line 2,290 ⟶ 2,678:
 
ErrorHandler:
PrintN(ErrorMessage()) : Goto label4</langsyntaxhighlight>
{{out}}
<pre>eins zwei eins zwei eins zwei - drei -</pre>
Line 2,298 ⟶ 2,686:
 
The "goto" module was an April Fool's joke, published on 1st April 2004. Yes, it works, but it's a joke nevertheless. Please don't use it in real code! For those who like computer languages with a sense of humour it can be downloded [http://entrian.com/goto/goto-1.0.tar.gz here]. It is well documented and comes with many examples. My favorite:
<syntaxhighlight lang="python">
<lang Python>
# Example 2: Restarting a loop:
from goto import goto, label
Line 2,312 ⟶ 2,700:
goto .start
print output, "\n"
</syntaxhighlight>
</lang>
It goes the extra mile and adds a <code>comefrom</code> keyword. This should be used only if you are evil and proud of it. It is reported to have caused maintenance programmers to have so strongly believed themselves insane that it became so. They are now under strong medication in padded cells. Basically whenever the code passes a label it jumps to the comefrom point. For best results I advise writing the comefrom code as far as possible from the label and using no comments near the label.
 
Line 2,320 ⟶ 2,708:
{{works with|BASIC256}}
{{works with|Yabasic}}
<langsyntaxhighlight lang="qbasic">
PRINT "First line."
GOSUB sub1
Line 2,342 ⟶ 2,730:
Finished:
PRINT "... with goto and gosub, thankfully."
END</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FutureBasic.</pre>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
<lang QB64>
' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic
' here a GOTO demo of loops FOR-NEXT and WHILE-WEND
Line 2,390 ⟶ 2,778:
Q = Q + 1
GoTo 2
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Line 2,412 ⟶ 2,800:
Quackery is an assembler insomuch as there is a direct, one to one, left to right correspondence between Quackery source code and the contents of the resultant nest, which is convenient. (There are a few simple-to-understand exceptions, and of course because the assembler is extensible, you can add more of those if you like, but generally it's easy to figure out where a specific item is in the nest.
 
As an example, this creates the control-flow word <code>jump-into</code>, which will start evaluation of a nest a specified distance in. <code>done</code> causes evaluation of the nest to terminate early (via <code>]done[</code>, which removes a pointer-offset pair from the call stack) and <code>again</code> causes a jump to the start of the nest. (<code>]again[</code> sets the number in the pair on the top of the call stack to 0.) So <code>5 jump-into</code> should start at item number 5 in the nest that follows it, echoing the numbers 2 and 3 to the screen, then branch back to the start end echo the numbers 0 and 1, then terminate.
 
To achieve this, <code>]'[</code> advances the offset on top of the return stack, like <code>]else[</code>, but also puts a copy of the item skipped over on the stack. (i.e. the nest following <code>jump-into</code> in the example) It puts this, with an offset of 0, onto the call stack (with <code>]do[</code>. Then it uses <code>' ]else[ swap of</code> to build a nest of the specified number of instances of <code>]else[</code>, and puts that on the call stack, so that it will be evaluated after exiting <code>jump-to</code>, and increment the offset of the top of the call stack (i.e. the nest following <code>jump-to</code>) that number of times.
 
<langsyntaxhighlight Quackerylang="quackery"> [ ]'[ ]do[ ' ]else[ swap of ]do[ ] is jump-into ( n --> )
 
5 jump-into
Line 2,422 ⟶ 2,810:
( 0 1 2 3 4 offsets of each item )
( 5 6 7 8 9 from start of nest )
2 echo 3 echo again ]</langsyntaxhighlight>
 
{{out}}
Line 2,432 ⟶ 2,820:
 
As a little example:
<langsyntaxhighlight lang="racket">#lang racket
(define (never-divides-by-zero return)
(displayln "I'm here")
Line 2,444 ⟶ 2,832:
; I'm here
; "Leaving" (because that's what the function returns)
</syntaxhighlight>
</lang>
 
Here, return is the program continuation being passed to the function, when it is called, the string "Leaving" i the result of the function and the following code is never executed.
Line 2,451 ⟶ 2,839:
Where we generate elements of a list one at a time:
 
<langsyntaxhighlight lang="racket">#lang racket
;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end-off-the-list)
(define (generate-one-element-at-a-time a-list)
Line 2,472 ⟶ 2,860:
;; time to return the generator
generator)
</syntaxhighlight>
</lang>
 
=={{header|Relation}}==
Line 2,481 ⟶ 2,869:
Retro allows the user to jump to any address.
 
<langsyntaxhighlight Retrolang="retro">:foo #19 &n:inc \ju...... #21 ;</langsyntaxhighlight>
 
When executed, the stack will contain 20; control does not return to the '''foo''' function.
Line 2,489 ⟶ 2,877:
 
===Label-based jumps===
<syntaxhighlight lang="raku" perl6line> outer-loop: loop {
inner-loop: loop {
# NYI # goto inner-loop if rand > 0.5; # Hard goto
Line 2,501 ⟶ 2,889:
LEAVE { say "Leaving outer loop block" }
LAST { say "Ending outer loop" }
}</langsyntaxhighlight>
Produces random output, but here's a representative run:
 
Line 2,517 ⟶ 2,905:
 
Continuations in Raku are currently limited to use in generators via the gather/take model:
<syntaxhighlight lang="raku" perl6line> my @list = lazy gather for ^100 -> $i {
if $i.is-prime {
say "Taking prime $i";
Line 2,524 ⟶ 2,912:
}
say @list[5];</langsyntaxhighlight>
This outputs:
 
Line 2,540 ⟶ 2,928:
 
Exceptions are fairly typical in Raku:
<syntaxhighlight lang="raku" perl6line> die "This is a generic, untyped exception";</langsyntaxhighlight>
Will walk up the stack until either some `CATCH` block intercepts the specific exception type or we exit the program.
 
But if a failure should be recoverable (e.g. execution might reasonably continue along another path) a failure is often the right choice. The fail operator is like "return", but the returned value will only be valid in boolean context or for testing definedness. Any other operation will produce the original exception with the original exception's execution context (e.g. traceback) along with the current context.
<syntaxhighlight lang="raku" perl6line> sub foo() { fail "oops" }
my $failure = foo;
say "Called foo";
say "foo not true" unless $failure;
say "foo not defined" unless $failure.defined;
say "incremented foo" if $failure++; # exception</langsyntaxhighlight>
Produces:
 
Line 2,563 ⟶ 2,951:
 
However, an exception can `.resume` in order to jump back to the failure point (this is why the stack is not unwound until after exception handling).
<syntaxhighlight lang="raku" perl6line> sub foo($i) {
if $i == 0 {
die "Are you sure you want /0?";
Line 2,577 ⟶ 2,965:
CATCH {
when ~$_ ~~ m:s/Are you sure/ { .resume; #`(yes, I'm sure) }
}</langsyntaxhighlight>
This code raises an exception on a zero input, but then resumes execution, divides be zero and then raises a divide by zero exception which is not caught:
 
Line 2,594 ⟶ 2,982:
<br>as long as the '''END''' or the '''DO''' loop isn't executed.
<br>The following used PC/REXX to illustrate this example.
<langsyntaxhighlight lang="rexx">/*REXX pgm demonstrates various jumps (GOTOs). In REXX, it's a SIGNAL. */
say 'starting...'
signal aJump
Line 2,612 ⟶ 3,000:
cJump: say 'and here we are at cJump.'
exit
end /*k*/</langsyntaxhighlight>
{{out}}
<pre>
Line 2,639 ⟶ 3,027:
As mentioned above some implementations may have restrictions on that.
This Signal jumps into a Do loop inside a Procedure:
<langsyntaxhighlight lang="rexx">i=13
signal label
say 'This is never executed'
Line 2,649 ⟶ 3,037:
End
Return
real_start:</langsyntaxhighlight>
Without the 'Signal real_start' which leads us out of the control structure the program would end with a syntax error when encountering the End correponding to the Do.
 
I recommend to use Signal only for condition handling and 'global' jumps to labels that are not within some structured constructs such as Do...End
An example:
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 12.12.2012 Walter Pachl
**********************************************************************/
Line 2,670 ⟶ 3,058:
Say 'argument must be a or b or omitted'
Exit
eoj: say 'here we could print statistics'</langsyntaxhighlight>
This can be useful when the different parts of the program span a few pages.
Also a Signal eoj in order to Exit from any point in the program to some final activities can be useful.
Line 2,682 ⟶ 3,070:
====Simple====
A simple example of labels and goto:
<langsyntaxhighlight lang="robotic">
. "The label 'touch' is used to let the player touch the robot"
. "to execute the following"
Line 2,696 ⟶ 3,084:
* "Label B was reached"
end
</syntaxhighlight>
</lang>
 
It prints "Label B was reached", skipping "label_a" entirely.
Line 2,702 ⟶ 3,090:
====Conditional====
This will jump to a given label, depending on the condition of "local1":
<langsyntaxhighlight lang="robotic">
set "local1" to 2
end
Line 2,717 ⟶ 3,105:
* "Label B was reached"
end
</syntaxhighlight>
</lang>
 
Since "local1" equals 2, it prints "Label B was reached".
Line 2,724 ⟶ 3,112:
When you goto a label, it chooses the top-most label name in the code.
However, with the use of "zap" and "restore", we can use the same label name multiple times in our code:
<langsyntaxhighlight lang="robotic">
end
: "touch"
Line 2,738 ⟶ 3,126:
restore "label_a" 1
end
</syntaxhighlight>
</lang>
 
When the first label is reached, it zaps "label_a" once. This allows us to reach the second label below. Conversely, restoring "label_a" allows us to go back to the first label once more.
Line 2,745 ⟶ 3,133:
With subroutines, we can jump to a given label and come back to where we left off after we called the inital "goto" statement.
To use these, the labels and the string supplied in the "goto" statements must have a number sign (#):
<langsyntaxhighlight lang="robotic">
. "The 'wait' statements are used to demonstrate what is happening"
set "local1" to 1
Line 2,775 ⟶ 3,163:
* "Label D was reached"
goto "#top"
</syntaxhighlight>
</lang>
 
The following is printed out in order:
<syntaxhighlight lang="text">
Label A was reached
Done with Label A
Line 2,784 ⟶ 3,172:
Label D was reached
Skipped finishing Label B and C
</syntaxhighlight>
</lang>
 
Using "#return", we go back up to the last "goto" statement called. However, using "#top" will ignore all the other subroutines called previously and go straight back to the first "goto" statement that started it all (in this case, goto "#label_b").
Line 2,793 ⟶ 3,181:
The next example abuses a continuation to solve [[FizzBuzz#Ruby]]. It is slower and more confusing than an ordinary loop.
{{libheader|continuation}}
<langsyntaxhighlight lang="ruby">require 'continuation' unless defined? Continuation
 
if a = callcc { |c| [c, 1] }
Line 2,814 ⟶ 3,202:
puts
c[c, i + 1]
end</langsyntaxhighlight>
 
This code uses the Continuation object <code>c</code> to jump to the top of the loop. For the first iteration, <code>callcc</code> creates <code>c</code> and returns <code>[c, 1]</code>. For later iterations, <code>callcc</code> returns <code>[c, i + 1]</code>. For the last iteration, <code>callcc</code> returns <code>nil</code> to break the loop.
 
=={{header|ScalaSNOBOL4}}==
 
Goto's are in the European programmer community [http://en.wikipedia.org/wiki/Considered_harmful considered harmful]. They are error-prune and not essential. A good programmer would stay away from that. Scala is not equipped with goto's.
Branches are the only kind of control structure in SNOBOL4. They come in three flavours (and one compound one):
 
* <code>:(LABEL_UNCONDITIONAL)</code>
* <code>:S(LABEL_ON_SUCCESS)</code>
* <code>:F(LABEL_ON_FAILURE)</code>
* <code>:S(LABEL_ON_SUCCESS)F(LABEL_ON_FAILURE)</code> or <code>:F(LABEL_ON_FAILURE)S(LABEL_ON_SUCCESS)</code>
 
<syntaxhighlight lang="snobol4">
* Demonstrate an unconditional branch.
OUTPUT = "Unconditional branch." :(SKIP1.START)
OUTPUT = "This will not display."
 
* Demonstrate a branch on success.
SKIP1.START v = 1
SKIP1.LOOP gt(v, 5) :S(SKIP2.START)
OUTPUT = "Iteration A" v
v = v + 1 :(SKIP1.LOOP)
 
* Demonstrate a branch on failure.
SKIP2.START v = 1
SKIP2.LOOP le(v, 5) :F(SKIP3.START)
OUTPUT = "Iteration B" v
v = v + 1 :(SKIP2.LOOP)
 
* Demonstrate a combined branch.
* Demonstrate also an indirect branch.
SKIP3.START v = 0
label = "SKIP3.LOOP"
SKIP3.LOOP v = v + 1
le(v, 5) :S(SKIP3.PRINT)F(EXIT)
SKIP3.PRINT OUTPUT = "Iteration C" v :($label)
 
EXIT OUTPUT = "Goodbye"
 
END
</syntaxhighlight>
 
{{Out}}
 
<pre>
Unconditional branch.
Iteration A1
Iteration A2
Iteration A3
Iteration A4
Iteration A5
Iteration B1
Iteration B2
Iteration B3
Iteration B4
Iteration B5
Iteration C1
Iteration C2
Iteration C3
Iteration C4
Iteration C5
Goodbye
</pre>
 
=={{header|SPL}}==
In SPL jumps can be non-conditional and conditional.
This is an example of non-conditional jump to label "myLabel":
<langsyntaxhighlight lang="spl">myLabel ->
...
:myLabel</langsyntaxhighlight>
This is an example of conditional jump to label "4", which is done if a=0:
<langsyntaxhighlight lang="spl">4 -> a=0
...
:4</langsyntaxhighlight>
In SPL it is possible not only jump, but also visit a label. "Visiting" a label means that program execution can be returned back to the place from where label was visited.
This is an example of visiting label "label 55":
<langsyntaxhighlight lang="spl">label 55 <->
#.output("1")
:label 55
#.output("2")
<-</langsyntaxhighlight>
and output is:
{{out}}
Line 2,848 ⟶ 3,294:
=={{header|SSEM}}==
The SSEM provides two jump instructions: the absolute jump <tt>000 <operand> to CI</tt> and the relative jump <tt>100 Add <operand> to CI</tt>. The operand in both cases is a memory address, whose contents are to be either loaded into the CI (Current Instruction) register or else added to it. Since CI is incremented <i>after</i> an instruction is executed, not before, the value stored at the operand address must be one less than the value we actually want. For example, this code accomplishes a jump to absolute address 20:
<langsyntaxhighlight lang="ssem">10000000000000000000000000000000 0. 1 to CI
11001000000000000000000000000000 1. 19</langsyntaxhighlight>
and this accomplishes a relative jump forward by five words:
<langsyntaxhighlight lang="ssem">10000000000001000000000000000000 0. Add 1 to CI
00100000000000000000000000000000 1. 4</langsyntaxhighlight>
 
=={{header|Tcl}}==
Tcl has both [[Exceptions#Tcl|exceptions]] and (from 8.6 onwards) [[Generator#Tcl|generators/coroutines]] but no unstructured goto ability. However, the main case where it might be desired, coding a general state machine, can be handled through metaprogramming (as discussed at some length on [http://wiki.tcl.tk/8363 the Tcler's Wiki]) so the absence is not strongly felt in practice.
 
=={{header|TXR}}==
{{trans|Common Lisp}}
 
TXR Lisp has a <code>tagbody</code> similar to Common Lisp. Like the Common Lisp one, it establishes an area of the program with forms labeled by symbols or numbers. The forms can branch to these symbols or numbers using <code>go</code>.
 
When a form initiates a branch, it is gracefully abandoned, which means that unwinding takes place: <code>unwind-protect</code> clean-up forms are called. Once the form is abandoned, control then transfers to the target form.
 
A <code>go</code> transfer may be used to jump out of a lexical closure, if the <code>tagbody</code> is still active. If a closure is captured in a <code>tagbody</code> which then terminates, and that closure is invoked, and tries to use <code>go</code> to jump to adjacent forms in that terminated tagbody, it is an error. An example of this follows, from an interactive session:
 
<pre>1> (let (fun)
(tagbody
again
(set fun (lambda () (go again))))
[fun])
** expr-1:4: return*: no block named #:tb-dyn-id-0028 is visible
** during evaluation of form (return* #:tb-id-0024
0)
** ... an expansion of (go again)
** which is located at expr-1:4</pre>
 
The above error messages reveal that TXR Lisp's <code>tagbody</code> is implemented by macros, and relies on a dynamic block return. It is provided mainly for compatibility; Common Lisp users using TXR Lisp may find it handy.
 
If the <code>tagbody</code> is still active when the lambda tries to perform a <code>go</code>, it works:
 
<pre>2> (let (fun)
(tagbody
(set fun (lambda () (go out)))
[fun]
(put-line "this is skipped")
out
(put-line "going out")))
going out
nil</pre>
 
 
The translated Common Lisp example follows:
 
<syntaxhighlight lang="txrlisp">(tagbody
beginning
(put-line "I am in the beginning")
(usleep 1000000)
(go end)
middle
(put-line "I am in the middle")
(usleep 1000000)
(go beginning)
end
(put-line "I am in the end")
(usleep 1000000)
(go middle))</syntaxhighlight>
{{out}}
<pre>
I am in the beginning
I am in the end
I am in the middle
I am in the beginning
I am in the end
I am in the middle
I am in the beginning
...</pre>
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Public Sub jump()
Debug.Print "VBA only allows"
GoTo 1
Line 2,876 ⟶ 3,383:
two:
Debug.Print "On <n> GoSub let you jump to the n-th label": Return
End Sub</langsyntaxhighlight>{{out}}
<pre>VBA only allows
jumps in procedures with GoTo
Line 2,888 ⟶ 3,395:
=={{header|VBScript}}==
In VBScript, there is no <code>goto</code> statement. It is a good thing for structured programming.
 
=={{header|V (Vlang)}}==
V (Vlang) and 'goto':
 
1) 'Goto' used only with 'unsafe' statements.
 
2) 'Goto' only allowed unconditionally jumping to a label within the function it belongs to.
 
3) Labelled 'break' and 'continue' statements are among the preferred alternatives to 'unsafe goto' usage.
 
4) Labelled 'break' and 'continue' allow easy breaking out of a nested loop or continuing within a containing loop.
<syntaxhighlight lang="v (vlang)">
// Unsafe 'goto' pseudo example:
 
if x {
// ...
if y {
unsafe {
goto my_label
}
}
// ...
}
my_label:
 
// Labelled 'break' and 'continue' example:
 
outer:
for idx := 0; idx < 4; idx++ {
for jdx := 0; jdx < 4; jdx++ {
if idx + jdx == 4 {continue outer}
if idx + jdx == 5 {break outer}
println(idx + jdx)
}
}
</syntaxhighlight>
 
=={{header|VTL-2}}==
Line 2,897 ⟶ 3,440:
If the expression does not evaluate to a line number present in the program, the program continues with the next highest line number or stops if there is no line with a number higher that the expression.<br>
The following program demonstrates this - prompiting the user for a label to goto. (In an expression, <code>?</code> indicates a value should be read from the console, assigning to <code>?</code> prints the assigned value)<br>
<langsyntaxhighlight VTL2lang="vtl2">1010 ?="@1010: Where to goto? ";
1020 #=?
1030 ?="@1030"
Line 2,904 ⟶ 3,447:
1060 #=1010
2000 ?="@2000"
2010 ?="Exiting..."</langsyntaxhighlight>
{{out}}
<pre>
Line 2,933 ⟶ 3,476:
 
The Fiber class also has a ''try'' method for catching errors (which won't be described here) and a static ''abort'' method which (unless caught) exits the script altogether if an error occurs.
<langsyntaxhighlight ecmascriptlang="wren">var func = Fn.new {
for (i in 1..10) {
if (i == 1) continue // jumps to next iteration when 'i' equals 1
Line 2,956 ⟶ 3,499:
System.print("yielding")
fiber.call() // resumes the fiber
return // would exit the module (and script) without error but won't be reached</langsyntaxhighlight>
 
{{out}}
Line 2,971 ⟶ 3,514:
resuming
aborting
[./jumpJump_anywhere line 17] in new(_) block argument
</pre>
 
Line 2,999 ⟶ 3,542:
{{works with|QBasic}}
{{works with|BASIC256}}
<langsyntaxhighlight lang="freebasic">print "First line."
gosub sub1
print "Fifth line."
Line 3,020 ⟶ 3,563:
Finished:
print "... with goto and gosub, thankfully."
end</langsyntaxhighlight>
{{out}}
<pre>Igual que la entrada de FutureBasic.</pre>
Line 3,034 ⟶ 3,577:
<code>JR</code> adds a signed displacement byte to the program counter. This takes one less byte to encode than a <code>JP</code> but cannot jump more than 127 bytes forward or 128 bytes backward. The programmer can either specify a constant value as the operand or a labeled section of code. If a label is used, the assembler will calculate the number of bytes between the <code>JR</code> instruction and that label, and will refuse to assemble the code if the label is too far away.
 
<langsyntaxhighlight lang="z80">and &01 ;returns 0 if the accumulator is even and 1 if odd. Also sets the zero flag accordingly.
jr z,SkipOddCode
;whatever you want to do when the accumulator is odd goes here, but it must be 127 bytes or fewer.
SkipOddCode:
;rest of program</langsyntaxhighlight>
 
 
A similar command called <code>DJNZ</code> is often used for looping. It decrements the B register and jumps if and only if B is nonzero. If B is zero, the <code>DJNZ</code> will do nothing and execution will move past it. Like all other jumping commands discussed so far, <code>DJNZ</code> will not alter the processor flags in any way. The same distance restriction of <code>JR</code> also applies to <code>DJNZ</code>. This is the equivalent of the <code>LOOP</code> instruction in [[x86 Assembly]].
 
<langsyntaxhighlight lang="z80">ld b,25
loop:
djnz loop ;loop 25 times.</langsyntaxhighlight>
 
 
Line 3,053 ⟶ 3,596:
<code>JR</code>,<code>JP</code>,<code>CALL</code>, and <code>RET</code> can be made conditional based on which flags are set. Essentially these are like <code>if</code> statements in a high-level language. If the condition specified by the command is not met, the command will have no effect; otherwise it will result in a jump.
 
<langsyntaxhighlight lang="z80">ret po ;return from subroutine if overflow has not occurred or the bit parity has an odd number of 1s.
call c, foo ;call "foo" if and only if the carry is set.
jp m,&ABCD ;jump to address &ABCD if the last operation resulted in a negative value.
jr z,25 ;jump 25 bytes forward if the last operation resulted in a zero. (Some assemblers such as VASM make you type "$+25")
;(Unlike the others, JR cannot jump based on the sign flag or parity/overflow flag.)</langsyntaxhighlight>
 
The Game Boy is more limited than the Z80 in this regard, as it has no sign or overflow flags! It can only use the zero and carry flags for jumps.
Line 3,066 ⟶ 3,609:
<code>JP (HL)</code> can be used to create a "trampoline," which lets you indirectly call a subroutine, provided that subroutine doesn't take <code>HL</code> as an argument. (Otherwise you'll get some unwanted results.) To do this, you need to know the address of the subroutine you wish to call, load it into HL, then <code>CALL</code> any address that contains either <code>JP (HL)</code> or the byte 0xE9. (<code>JP (HL)</code>'s bytecode is 0xE9). Once you do this, execution will effectively "call" the desired routine. For this to work, the desired routine must end in a <code>RET</code>, and balance the stack properly. That way, when it does <code>RET</code>, it will <code>RET</code> to where you were just after the <code>CALL</code>.
 
<langsyntaxhighlight lang="z80">
ld hl,foo ;rather than directly specifying "foo", you would normally retrieve it by indexing a table.
;This was done only to keep the example as simple as possible.
Line 3,081 ⟶ 3,624:
foo:
ld a,0
ret</langsyntaxhighlight>
 
''NB: If your hardware allows you to define the <code>RST</code> calls to whatever you like, you can speed this up even more by setting one of them to <code>JP (HL)</code>, and invoking that RST as your trampoline rather than the call. The only downside is that you can't conditionally execute an <code>RST</code>, but if you were using a trampoline it likely wasn't going to be conditional anyway.''
Line 3,102 ⟶ 3,645:
{{omit from|Oberon-2}}
{{omit from|UNIX Shell|Does not have goto or line labels, but can break from nested loops}}
{{omit from|Insitux}}
9,476

edits