Jump anywhere: Difference between revisions
Puppydrum64 (talk | contribs) |
PascalABC.NET |
||
(33 intermediate revisions by 16 users not shown) | |||
Line 23: | Line 23: | ||
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. |
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. |
||
<br><br> |
<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}}== |
=={{header|6502 Assembly}}== |
||
Line 29: | Line 37: | ||
===Direct Jump=== |
===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) |
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) |
||
< |
<syntaxhighlight lang="6502asm">JMP PrintChar ; jump to the label "PrintChar" where a routine to print a letter to the screen is located.</syntaxhighlight> |
||
===Indirect Jump=== |
===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: |
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: |
||
< |
<syntaxhighlight lang="6502asm">lda #<PrintChar ;load into A the low byte of the address that PrintChar references. |
||
sta $00 |
sta $00 |
||
lda #>PrintChar ;load into A the high byte of the address that PrintChar references. |
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 |
sta $01 ;these need to be stored low then high because the 6502 is a little-endian cpu |
||
JMP ($00) ;dereferences to JMP PrintChar</ |
JMP ($00) ;dereferences to JMP PrintChar</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight 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 |
JumpTable_Hi: db >PrintChar, >WaitChar, >ReadKeys, >MoveMouse ;each is the high byte of a memory address |
||
Line 48: | Line 56: | ||
lda JumpTable_Hi,x |
lda JumpTable_Hi,x |
||
sta $11 |
sta $11 |
||
JMP ($0010)</ |
JMP ($0010)</syntaxhighlight> |
||
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. |
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: | Line 62: | ||
Another way to do this is with a "jump block." |
Another way to do this is with a "jump block." |
||
< |
<syntaxhighlight lang="6502asm">.org $8000 |
||
JMP PrintChar |
JMP PrintChar |
||
JMP WaitChar |
JMP WaitChar |
||
JMP ReadKeys |
JMP ReadKeys |
||
JMP MoveMouse |
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. |
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. |
||
< |
<syntaxhighlight lang="6502asm">lda $80 |
||
sta $21 |
sta $21 |
||
txa |
txa |
||
Line 68: | Line 76: | ||
adc #$03 |
adc #$03 |
||
sta $20 |
sta $20 |
||
JMP ($0020)</ |
JMP ($0020)</syntaxhighlight> |
||
If X was 0, the JMP takes us to WaitChar. |
If X was 0, the JMP takes us to WaitChar. |
||
Line 80: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="6502asm">JumpTable: |
||
word PrintChar |
word PrintChar |
||
word PrintString |
word PrintString |
||
Line 86: | Line 94: | ||
ldx #$02 |
ldx #$02 |
||
JMP (JumpTable,x) ;dereferences to JMP PrintString</ |
JMP (JumpTable,x) ;dereferences to JMP PrintString</syntaxhighlight> |
||
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. |
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: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="6502asm">ReturnTable: dw PrintChar-1,WaitChar-1,ReadKeys-1,MoveMouse-1</syntaxhighlight> |
||
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). |
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. |
We'll assume for the code below that the accumulator contains such a variable right now. |
||
< |
<syntaxhighlight lang="6502asm"> |
||
;execution is currently here |
;execution is currently here |
||
JSR UseReturnTable ;the address just after this label is pushed onto the stack. |
JSR UseReturnTable ;the address just after this label is pushed onto the stack. |
||
Line 114: | Line 122: | ||
RTS ;this "RTS" actually takes you to the desired subroutine. |
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, |
;The top two bytes of the stack are popped, the low byte is incremented by 1, |
||
;and this value becomes the new program counter.</ |
;and this value becomes the new program counter.</syntaxhighlight> |
||
Now all of that was a bit confusing wasn't it? Essentially this "abuses" the following concepts: |
Now all of that was a bit confusing wasn't it? Essentially this "abuses" the following concepts: |
||
Line 130: | Line 138: | ||
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. |
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== |
===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>. |
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>. |
||
Line 139: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="68000devpac">bra foo |
||
nop ;execution will never reach here |
nop ;execution will never reach here |
||
foo: |
foo: |
||
Line 146: | Line 154: | ||
BGE D1_Is_Greater_Than_Or_Equal_To_D0 |
BGE D1_Is_Greater_Than_Or_Equal_To_D0 |
||
; your code for what happens when D1 is less than D0 goes here |
; your code for what happens when D1 is less than D0 goes here |
||
D1_Is_Greater_Than_Or_Equal_To_D0:</ |
D1_Is_Greater_Than_Or_Equal_To_D0:</syntaxhighlight> |
||
===Absolute Jumps=== |
===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: |
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: |
||
< |
<syntaxhighlight lang="68000devpac">JSR foo: |
||
; this is somewhere far away from the JSR above |
; this is somewhere far away from the JSR above |
||
foo: |
foo: |
||
MOVE.L D0,(SP)+ |
MOVE.L D0,(SP)+ |
||
RTS ;the CPU will "return" to the value that was in D0, not the actual return address.</ |
RTS ;the CPU will "return" to the value that was in D0, not the actual return address.</syntaxhighlight> |
||
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) |
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) |
||
< |
<syntaxhighlight lang="68000devpac">;For this example, we want to execute "ReadJoystick" |
||
MOVE.W D0,#1 |
MOVE.W D0,#1 |
||
JSR Retpoline |
JSR Retpoline |
||
Line 175: | Line 183: | ||
SubroutineTable: |
SubroutineTable: |
||
DC.L MoveMouse, DC.L ReadJoystick, DC.L ReadKeyboard, DC.L PrintString</ |
DC.L MoveMouse, DC.L ReadJoystick, DC.L ReadKeyboard, DC.L PrintString</syntaxhighlight> |
||
===Indirect Jumps=== |
===Indirect Jumps=== |
||
Line 184: | Line 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. |
<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. |
||
< |
<syntaxhighlight lang="asm">JCXZ bar |
||
foo: |
foo: |
||
LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo |
LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo |
||
bar:</ |
bar:</syntaxhighlight> |
||
<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. |
<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 193: | Line 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. |
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}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada"> |
||
procedure Goto_Test is |
procedure Goto_Test is |
||
begin |
begin |
||
Line 245: | Line 425: | ||
end Goto_Test; |
end Goto_Test; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
Line 264: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="arm assembly">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</ |
LDR PC,[R0] ;loads the program counter with the 32-bit value at the memory location specified by R0</syntaxhighlight> |
||
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>. |
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>. |
||
< |
<syntaxhighlight lang="arm assembly">PUSH {R0-R12,LR} |
||
POP {R0-R12,PC}</ |
POP {R0-R12,PC}</syntaxhighlight> |
||
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 |
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 |
||
< |
<syntaxhighlight lang="arm assembly">STMFD sp!,{r0-r12,lr} |
||
LDMFD sp!,{r0-r12,pc}</ |
LDMFD sp!,{r0-r12,pc}</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
Line 282: | Line 462: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="ahk">; Define a function. |
||
function() |
function() |
||
{ |
{ |
||
Line 318: | Line 498: | ||
Suspended |
Suspended |
||
*/</ |
*/</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
< |
<syntaxhighlight lang="basic">10 GOTO 100: REM jump to a specific line |
||
20 RUN 200: REM start the program running from a specific line</ |
20 RUN 200: REM start the program running from a specific line</syntaxhighlight> |
||
Some versions of basic allow line labels to be used. Here we jump to a label: |
Some versions of basic allow line labels to be used. Here we jump to a label: |
||
{{works with|BaCon}} |
{{works with|BaCon}} |
||
{{works with|QuickBASIC}} |
{{works with|QuickBASIC}} |
||
<lang |
<syntaxhighlight lang="qbasic">GOTO mylabel</syntaxhighlight> |
||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
caveat: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html |
caveat: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html |
||
< |
<syntaxhighlight lang="applesoftbasic"> 0 REM GOTO |
||
100 GOTO 110 : REM JUMP TO A SPECIFIC LINE |
100 GOTO 110 : REM JUMP TO A SPECIFIC LINE |
||
110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE |
110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE |
||
Line 351: | Line 531: | ||
280 STOP : REM BREAK THE PROGRAM |
280 STOP : REM BREAK THE PROGRAM |
||
290 END : REM END THE PROGRAM |
290 END : REM END THE PROGRAM |
||
300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0</ |
300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0</syntaxhighlight> |
||
< |
<syntaxhighlight lang="applesoftbasic">CONT : REM CONTINUE, JUMP BACK TO WHERE THE PROGRAM STOPPED</syntaxhighlight> |
||
==={{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}}== |
==={{header|BASIC256}}=== |
||
BASIC256 supports both <code>goto</code> and <code>gosub</code>. |
BASIC256 supports both <code>goto</code> and <code>gosub</code>. |
||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
{{works with|Yabasic}} |
{{works with|Yabasic}} |
||
< |
<syntaxhighlight lang="freebasic">print "First line." |
||
gosub sub1 |
gosub sub1 |
||
print "Fifth line." |
print "Fifth line." |
||
Line 405: | Line 559: | ||
Finished: |
Finished: |
||
print "... with goto and gosub, thankfully." |
print "... with goto and gosub, thankfully." |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Igual que la entrada de FutureBasic.</pre> |
<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}}== |
=={{header|C}}== |
||
C has <code>goto LABEL</code> keyword. |
C has <code>goto LABEL</code> keyword. |
||
< |
<syntaxhighlight lang="c"> if (x > 0) goto positive; |
||
else goto negative; |
else goto negative; |
||
Line 421: | Line 713: | ||
both: |
both: |
||
...</ |
...</syntaxhighlight> |
||
The label must be literal, not computed at run time. This won't work: |
The label must be literal, not computed at run time. This won't work: |
||
< |
<syntaxhighlight lang="c">goto (x > 0 ? positive : negative);</syntaxhighlight> |
||
<!-- Except if you're using GCC extensions, when you can do something that's very similar to that. Scary stuff! --> |
<!-- 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:< |
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:<syntaxhighlight lang="c">for (i = 0; ...) { |
||
for (j = 0; ...) { |
for (j = 0; ...) { |
||
if (condition_met) goto finish; |
if (condition_met) goto finish; |
||
} |
} |
||
}</ |
}</syntaxhighlight>although you can (not that you ''should'') jump into a loop, too:<syntaxhighlight lang="c"> goto danger; |
||
for (i = 0; i < 10; i++) { |
for (i = 0; i < 10; i++) { |
||
danger: /* unless you jumped here with i set to a proper value */ |
danger: /* unless you jumped here with i set to a proper value */ |
||
printf("%d\n", i); |
printf("%d\n", i); |
||
}</ |
}</syntaxhighlight> |
||
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]]. |
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. |
The best application for goto is error handling, this simplifies the resource clean up of a large function. |
||
Line 440: | Line 732: | ||
<syntaxhighlight lang="c"> |
|||
<lang c> |
|||
char *str; |
char *str; |
||
int *array; |
int *array; |
||
Line 466: | Line 758: | ||
...// read in the csv file and convert to integers |
...// read in the csv file and convert to integers |
||
</syntaxhighlight> |
|||
</lang> |
|||
<syntaxhighlight lang="c"> |
|||
<lang c> |
|||
char *str; |
char *str; |
||
int *array; |
int *array; |
||
Line 495: | Line 787: | ||
exit: |
exit: |
||
return; |
return; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="csharp">if (x > 0) goto positive; |
||
else goto negative; |
else goto negative; |
||
Line 509: | Line 801: | ||
both: |
both: |
||
...</ |
...</syntaxhighlight> |
||
The label must be literal, not computed at run time. This won't work: |
The label must be literal, not computed at run time. This won't work: |
||
< |
<syntaxhighlight lang="csharp">goto (x > 0 ? positive : negative);</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="csharp">for (i = 0; ...) { |
||
for (j = 0; ...) { |
for (j = 0; ...) { |
||
if (condition_met) goto finish; |
if (condition_met) goto finish; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
The label must be in scope, so you cannot jump into a loop. This will not compile: |
The label must be in scope, so you cannot jump into a loop. This will not compile: |
||
< |
<syntaxhighlight lang="csharp">goto danger; |
||
for (i = 0; i < 10; i++) { |
for (i = 0; i < 10; i++) { |
||
danger: |
danger: |
||
Console.WriteLine(i); |
Console.WriteLine(i); |
||
}</ |
}</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="csharp">int i = 0; |
||
tryAgain: |
tryAgain: |
||
try { |
try { |
||
Line 538: | Line 830: | ||
finally { |
finally { |
||
//goto end; //Error |
//goto end; //Error |
||
}</ |
}</syntaxhighlight> |
||
Another usage of <code>goto</code> is to jump between <code>case</code> labels inside a <code>switch</code> statement: |
Another usage of <code>goto</code> is to jump between <code>case</code> labels inside a <code>switch</code> statement: |
||
< |
<syntaxhighlight lang="csharp">public int M(int n) { |
||
int result = 0; |
int result = 0; |
||
switch (n) { |
switch (n) { |
||
Line 555: | Line 847: | ||
} |
} |
||
return result; |
return result; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Like C, C++ also has a <code>goto LABEL</code> statement which can be used to jump within a function. |
Like C, C++ also has a <code>goto LABEL</code> statement which can be used to jump within a function. |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <utility> |
#include <utility> |
||
Line 605: | Line 897: | ||
cout << "k = " << k << "\n"; // k was never initialized, accessing it is undefined behavior |
cout << "k = " << k << "\n"; // k was never initialized, accessing it is undefined behavior |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 619: | Line 911: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobolfree"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. |
PROGRAM-ID. jumps-program. |
||
* Nobody writes like this, of course; but... |
* Nobody writes like this, of course; but... |
||
PROCEDURE DIVISION. |
|||
PROCEDURE DIVISION. |
|||
* You can jump anywhere you like. |
* You can jump anywhere you like. |
||
start-paragraph. |
|||
START-PARAGRAPH. |
|||
GO TO |
GO TO an-arbitrary-paragraph. |
||
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 |
* 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, |
* destinations can be changed at will, from anywhere in the program, |
||
* at run time. |
* at run time. |
||
GO TO |
GO TO start-paragraph. |
||
* But bear in mind: once you get there, the GO TO no longer goes to |
* But bear in mind: once you get there, the GO TO no longer goes to |
||
* where it says it 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. |
* You think that's bad? You ain't seen nothing. |
||
GO TO |
GO TO yet-another-paragraph. |
||
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}} |
{{out}} |
||
<pre>Edsger who now? |
<pre>Edsger who now? |
||
Line 649: | Line 949: | ||
'''COBOL''' also supports computed go to phrases, given a list of labels (paragraph names) and an integer index into that list. |
'''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}}== |
=={{header|Common Lisp}}== |
||
In Common Lisp you can jump anywhere inside a tagbody. |
In Common Lisp you can jump anywhere inside a tagbody. |
||
< |
<syntaxhighlight lang="lisp"> |
||
(tagbody |
(tagbody |
||
beginning |
beginning |
||
Line 668: | Line 973: | ||
(sleep 1) |
(sleep 1) |
||
(go middle)) |
(go middle)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 683: | Line 988: | ||
=={{header|Computer/zero Assembly}}== |
=={{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: |
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: |
||
< |
<syntaxhighlight lang="czasm"> LDA goto |
||
SUB somewhere |
SUB somewhere |
||
ADD somewhereElse |
ADD somewhereElse |
||
STA goto |
STA goto |
||
goto: JMP somewhere</ |
goto: JMP somewhere</syntaxhighlight> |
||
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.) |
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 694: | Line 999: | ||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
< |
<syntaxhighlight lang="dcl">$ return ! ignored since we haven't done a gosub yet |
||
$ |
$ |
||
$ if p1 .eqs. "" then $ goto main |
$ if p1 .eqs. "" then $ goto main |
||
Line 764: | Line 1,069: | ||
$ sub4: subroutine |
$ sub4: subroutine |
||
$ exit |
$ exit |
||
$ endsubroutine</ |
$ endsubroutine</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @jump_anywhere |
<pre>$ @jump_anywhere |
||
Line 865: | Line 1,170: | ||
Déjà Vu supports continuations: |
Déjà Vu supports continuations: |
||
< |
<syntaxhighlight lang="dejavu">example: |
||
!print "First part" |
!print "First part" |
||
yield |
yield |
||
Line 872: | Line 1,177: | ||
local :continue example |
local :continue example |
||
!print "Interrupted" |
!print "Interrupted" |
||
continue</ |
continue</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>First part |
<pre>First part |
||
Line 883: | Line 1,188: | ||
Every function/procedure must have your own labels, globals labels won't work in local functions. |
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. |
The label must be literal, not computed at run time. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
x: Integer = 5; |
x: Integer = 5; |
||
Line 905: | Line 1,210: | ||
readln; |
readln; |
||
end. |
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. |
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. |
If the loop variable has a value out range loop limits, then you cause a intinity loop. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
label |
label |
||
inloop, outloop; |
inloop, outloop; |
||
Line 927: | Line 1,232: | ||
readln; |
readln; |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 942: | Line 1,247: | ||
This won't work. |
This won't work. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
label |
label |
||
tryAgain, finished; |
tryAgain, finished; |
||
Line 960: | Line 1,265: | ||
readln; |
readln; |
||
end. |
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}}== |
=={{header|Erlang}}== |
||
Jumps are limited to [[Exceptions]]. |
Jumps are limited to [[Exceptions]]. |
||
Line 966: | Line 1,337: | ||
=={{header|ERRE}}== |
=={{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: |
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: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
PROGRAM GOTO_ERR |
PROGRAM GOTO_ERR |
||
Line 986: | Line 1,357: | ||
IF J<>0 THEN GOTO 100 END IF |
IF J<>0 THEN GOTO 100 END IF |
||
END PROGRAM |
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). |
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 996: | Line 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>. |
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>. |
||
< |
<syntaxhighlight lang="factor">USING: continuations prettyprint ; |
||
current-continuation short.</ |
current-continuation short.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,006: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="factor">USING: continuations math prettyprint ; |
||
[ 10 2 / . continue 1 0 / . ] callcc0</ |
[ 10 2 / . continue 1 0 / . ] callcc0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,015: | Line 1,386: | ||
We can even reify a continuation while taking an object back with us. |
We can even reify a continuation while taking an object back with us. |
||
< |
<syntaxhighlight lang="factor">USING: continuations kernel math ; |
||
[ 10 2 / swap continue-with 1 0 / ] callcc1</ |
[ 10 2 / swap continue-with 1 0 / ] callcc1</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,053: | Line 1,424: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">\ this prints five lines containing elements from the two |
||
\ words 'proc1' and 'proc2'. gotos are used here to jump |
\ words 'proc1' and 'proc2'. gotos are used here to jump |
||
\ into and out of the two words at various points, as well |
\ into and out of the two words at various points, as well |
||
Line 1,081: | Line 1,452: | ||
5 1 proc2 |
5 1 proc2 |
||
bye</ |
bye</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight 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 2 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5 |
||
line 3 --> 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 4 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5 |
||
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</ |
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</syntaxhighlight> |
||
< |
<syntaxhighlight lang="forth">\ this is congruent to the previous demonstration, employing |
||
\ a data structure to store goto/jump addresses instead of |
\ a data structure to store goto/jump addresses instead of |
||
\ separate variables, and two additional words 'mark_goto' and |
\ separate variables, and two additional words 'mark_goto' and |
||
Line 1,120: | Line 1,491: | ||
: go 5 1 6 goto ; go |
: go 5 1 6 goto ; go |
||
bye</ |
bye</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight 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 2 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5 |
||
line 3 --> 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 4 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5 |
||
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</ |
line 5 --> item6 item1 item7 item2 item8 item3 item9 item4 item10 item5</syntaxhighlight> |
||
< |
<syntaxhighlight lang="forth">\ works with ficl, pfe, gforth, bigforth, and vfx. |
||
\ swiftforth may crash, iforth does not function. |
\ swiftforth may crash, iforth does not function. |
||
Line 1,167: | Line 1,538: | ||
5 1 go |
5 1 go |
||
bye</ |
bye</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight 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 2 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8 |
||
iteration 3 --> 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 4 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8 |
||
iteration 5 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8</ |
iteration 5 --> goto1 goto3 goto5 goto7 goto9 goto2 goto4 goto6 goto8</syntaxhighlight> |
||
Line 1,180: | Line 1,551: | ||
Although Forth was designed to be a structured programming language it is simple to add a generic jump anywhere. |
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. |
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. |
||
< |
<syntaxhighlight lang="forth">: GOTO ['] EXECUTE ;</syntaxhighlight> |
||
TEST |
TEST |
||
< |
<syntaxhighlight lang="forth">: WORLD ." World!" ; |
||
: HELLO ." Hello" ; |
: HELLO ." Hello" ; |
||
GOTO CR GOTO HELLO GOTO SPACE GOTO WORLD |
GOTO CR GOTO HELLO GOTO SPACE GOTO WORLD |
||
Hello World!</ |
Hello World!</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 1,229: | Line 1,600: | ||
The following program demonstrate the use of the various 'Goto' constructs in the -lang fb dialect only: |
The following program demonstrate the use of the various 'Goto' constructs in the -lang fb dialect only: |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
' compiled with -lang fb (the default) and -e switches |
' compiled with -lang fb (the default) and -e switches |
||
Line 1,278: | Line 1,649: | ||
Print |
Print |
||
Print "Pres any key to quit" |
Print "Pres any key to quit" |
||
Print</ |
Print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,297: | Line 1,668: | ||
All that said, don't use spaghetti code -- use functions. You can still by spark plugs for a 1985 Yugo, but why? |
All that said, don't use spaghetti code -- use functions. You can still by spark plugs for a 1985 Yugo, but why? |
||
< |
<syntaxhighlight lang="futurebasic"> |
||
window 1 |
|||
include "ConsoleWindow" |
|||
print "First line." |
print "First line." |
||
Line 1,317: | Line 1,688: | ||
"Outa here" |
"Outa here" |
||
print "... with goto and gosub, thankfully." |
print "... with goto and gosub, thankfully." |
||
end |
|||
HandleEvents |
|||
</lang> |
|||
</syntaxhighlight> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,336: | Line 1,708: | ||
For example: |
For example: |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,356: | Line 1,728: | ||
k++ |
k++ |
||
fmt.Println(k) |
fmt.Println(k) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,372: | Line 1,744: | ||
4 |
4 |
||
</pre> |
</pre> |
||
::< |
::<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,406: | Line 1,778: | ||
func init() { |
func init() { |
||
fmt.Println("run first") |
fmt.Println("run first") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
Line 1,417: | Line 1,789: | ||
First some boilerplate, where we define labels and goto "operator". |
First some boilerplate, where we define labels and goto "operator". |
||
< |
<syntaxhighlight lang="haskell">import Control.Monad.Cont |
||
data LabelT r m = LabelT (ContT r m ()) |
data LabelT r m = LabelT (ContT r m ()) |
||
Line 1,429: | Line 1,801: | ||
runProgram :: Monad m => ContT r m r -> m r |
runProgram :: Monad m => ContT r m r -> m r |
||
runProgram program = runContT program return</ |
runProgram program = runContT program return</syntaxhighlight> |
||
Here is example of using labels in IO: |
Here is example of using labels in IO: |
||
< |
<syntaxhighlight lang="haskell">main = runProgram $ |
||
do |
do |
||
start <- label |
start <- label |
||
Line 1,440: | Line 1,812: | ||
then do lift $ putStrLn "Name can't be empty!" |
then do lift $ putStrLn "Name can't be empty!" |
||
goto start |
goto start |
||
else lift $ putStrLn ("Hello, " ++ name)</ |
else lift $ putStrLn ("Hello, " ++ name)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,452: | Line 1,824: | ||
We can build tiny EDSL to get rid of explicit lifting and to add refferences: |
We can build tiny EDSL to get rid of explicit lifting and to add refferences: |
||
< |
<syntaxhighlight lang="haskell">import Data.IORef |
||
readInt = lift $ readLn >>= newIORef |
readInt = lift $ readLn >>= newIORef |
||
get ref = lift $ readIORef ref |
get ref = lift $ readIORef ref |
||
set ref expr = lift $ modifyIORef ref (const expr) |
set ref expr = lift $ modifyIORef ref (const expr) |
||
output expr = lift $ putStrLn expr</ |
output expr = lift $ putStrLn expr</syntaxhighlight> |
||
and implement famous Euclid's algorithm as an imperative program: |
and implement famous Euclid's algorithm as an imperative program: |
||
< |
<syntaxhighlight lang="haskell">gcdProg = runProgram $ callCC $ \exit -> -- <--------+ |
||
do -- | |
do -- | |
||
start <- label -- <-----+ | |
start <- label -- <-----+ | |
||
Line 1,478: | Line 1,850: | ||
when (n > m) $ set nr (n - m) -- | |
when (n > m) $ set nr (n - m) -- | |
||
when (m > n) $ set mr (m - n) -- | |
when (m > n) $ set mr (m - n) -- | |
||
goto loop -- ---+</ |
goto loop -- ---+</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 1,492: | Line 1,864: | ||
In native Haskell such flow jumps are done by function calls: |
In native Haskell such flow jumps are done by function calls: |
||
< |
<syntaxhighlight lang="haskell">gcdFProg = start |
||
where |
where |
||
start = do |
start = do |
||
Line 1,508: | Line 1,880: | ||
| n == m = n |
| n == m = n |
||
| n < m = loop n (m-n) |
| n < m = loop n (m-n) |
||
| n > m = loop (n-m) m</ |
| n > m = loop (n-m) m</syntaxhighlight> |
||
Or without explicit recursion and branching: |
Or without explicit recursion and branching: |
||
< |
<syntaxhighlight lang="haskell">import Control.Applicative |
||
import Control.Monad.Trans.Maybe |
import Control.Monad.Trans.Maybe |
||
Line 1,523: | Line 1,895: | ||
process = gcd <$> (lift readLn >>= exitOn 0) <*> lift readLn |
process = gcd <$> (lift readLn >>= exitOn 0) <*> lift readLn |
||
exitOn n x = if x == n then empty else pure x</ |
exitOn n x = if x == n then empty else pure x</syntaxhighlight> |
||
=={{header|i}}== |
=={{header|i}}== |
||
< |
<syntaxhighlight lang="i">//'i' does not have goto statements, instead control flow is the only legal way to navigate the program. |
||
concept there() { |
concept there() { |
||
print("Hello there") |
print("Hello there") |
||
Line 1,554: | Line 1,926: | ||
//Move to the code contained in the 'there' function. |
//Move to the code contained in the 'there' function. |
||
there() |
there() |
||
}</ |
}</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,560: | Line 1,932: | ||
For example: |
For example: |
||
< |
<syntaxhighlight lang="j">F=: verb define |
||
smoutput 'Now we are in F' |
smoutput 'Now we are in F' |
||
G'' |
G'' |
||
Line 1,573: | Line 1,945: | ||
F'' |
F'' |
||
Now we are in F |
Now we are in F |
||
Now we are in G</ |
Now we are in G</syntaxhighlight> |
||
J also supports jumps to labels within a definition: |
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): |
||
< |
<syntaxhighlight lang="j">H=: verb define |
||
smoutput 'a' |
smoutput 'a' |
||
label_b. |
label_b. |
||
Line 1,594: | Line 1,966: | ||
c |
c |
||
g |
g |
||
e</ |
e</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
The closest thing that Java has to a "goto" is labelled loops: |
The closest thing that Java has to a "goto" is labelled loops: |
||
< |
<syntaxhighlight lang="java">loop1: while (x != 0) { |
||
loop2: for (int i = 0; i < 10; i++) { |
loop2: for (int i = 0; i < 10; i++) { |
||
loop3: do { |
loop3: do { |
||
Line 1,615: | Line 1,987: | ||
} |
} |
||
//loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed |
//loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed |
||
}</ |
}</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="java"> |
||
public class FizzBuzzThrower { |
public class FizzBuzzThrower { |
||
public static void main( String [] args ) { |
public static void main( String [] args ) { |
||
Line 1,636: | Line 2,008: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,644: | Line 2,016: | ||
jq supports named labels ("label $NAME") and break statements ("break $NAME"). Usage |
jq supports named labels ("label $NAME") and break statements ("break $NAME"). Usage |
||
follows the pattern: |
follows the pattern: |
||
< |
<syntaxhighlight lang="jq">label $out | ... break $out ...</syntaxhighlight> |
||
When, during program execution, a "break" statement is encountered, the program |
When, during program execution, a "break" statement is encountered, the program |
||
Line 1,655: | Line 2,027: | ||
Break statements are used to interrupt a generator. For example, to emit |
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: |
the least positive integer satisfying sin(1/N) == (1/N) using IEEE 64-bit arithmetic: |
||
< |
<syntaxhighlight lang="jq">label $out | 1e7 | while(true; .+1) | if (1/.) | . == sin then (., break $out) else empty end</syntaxhighlight> |
||
Here, the "while" filter is an unbounded generator. The answer is 46530688. |
Here, the "while" filter is an unbounded generator. The answer is 46530688. |
||
Line 1,663: | Line 2,035: | ||
Indeed, a better way to solve the type of problem mentioned above is by using one of the jq-provided control structures. |
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: |
For example, the above problem can be solved more succinctly and transparently using until/2: |
||
< |
<syntaxhighlight lang="jq">1e7 | until(1/. | . == sin; .+1)</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="julia"> |
||
function example() |
function example() |
||
println("Hello ") |
println("Hello ") |
||
Line 1,676: | Line 2,048: | ||
println("world") |
println("world") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Line 1,684: | Line 2,056: | ||
For example: |
For example: |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 1,699: | Line 2,071: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,723: | Line 2,095: | ||
* Lingo supports "unwinding the call stack" via the abort command that exits the current call stack: |
* Lingo supports "unwinding the call stack" via the abort command that exits the current call stack: |
||
< |
<syntaxhighlight lang="lingo">on foo |
||
abort() |
abort() |
||
end |
end |
||
Line 1,730: | Line 2,102: | ||
foo() |
foo() |
||
put "This will never be printed" |
put "This will never be printed" |
||
end</ |
end</syntaxhighlight> |
||
* Rarely used, but Lingo supports saving a continuation via the play ... play done construct: |
* Rarely used, but Lingo supports saving a continuation via the play ... play done construct: |
||
< |
<syntaxhighlight lang="lingo">on testPlayDone () |
||
-- Start some asynchronous process (like e.g. a HTTP request). |
-- Start some asynchronous process (like e.g. a HTTP request). |
||
Line 1,744: | Line 2,116: | ||
-- The following will be executed only after 'play done' was called in the asynchronous process code |
-- 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 |
put "Done. The asynchronous process returned the result:" && _global.result |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
Line 1,751: | Line 2,123: | ||
=={{header|Lua}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="lua">-- Forward jump |
||
goto skip_print |
goto skip_print |
||
print "won't print" |
print "won't print" |
||
Line 1,788: | Line 2,160: | ||
end |
end |
||
print "not found" |
print "not found" |
||
::exit::</ |
::exit::</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Line 1,797: | Line 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) |
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=== |
===Using GOTO and GOSUB=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
Module Alfa { |
Module Alfa { |
||
Line 1,831: | Line 2,203: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Simulate Run Basic Entry=== |
===Simulate Run Basic Entry=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module LikeRunBasic { |
Module LikeRunBasic { |
||
for i = 1 to 10 |
for i = 1 to 10 |
||
Line 1,858: | Line 2,230: | ||
} |
} |
||
LikeRunBasic |
LikeRunBasic |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Simulate Go Entry=== |
===Simulate Go Entry=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module LikeGo { |
Module LikeGo { |
||
\\ simulate Go for |
\\ simulate Go for |
||
Line 1,944: | Line 2,316: | ||
LikeGo_No_Labels |
LikeGo_No_Labels |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
Line 1,953: | Line 2,325: | ||
=={{header|MBS}}== |
=={{header|MBS}}== |
||
<lang |
<syntaxhighlight lang="mbs">goto mylabel;</syntaxhighlight> |
||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>БП XX</ |
<syntaxhighlight lang="text">БП XX</syntaxhighlight> |
||
'''XX''' is any address. |
'''XX''' is any address. |
||
Line 1,968: | Line 2,340: | ||
* <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>. |
* <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>. |
||
* <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>. |
* <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> |
|||
Line 1,977: | Line 2,361: | ||
Some interpreters will allow you jump between blocks of the same depth. Others will let you leave, but not enter, a block. |
Some interpreters will allow you jump between blocks of the same depth. Others will let you leave, but not enter, a block. |
||
< |
<syntaxhighlight lang="mumps"> ;Go to a label within the program file |
||
Goto Label |
Goto Label |
||
;Go to a line below a label |
;Go to a line below a label |
||
Line 1,993: | Line 2,377: | ||
. Goto Out |
. Goto Out |
||
Out Quit |
Out Quit |
||
Goto NoNo+2</ |
Goto NoNo+2</syntaxhighlight> |
||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
Line 1,999: | Line 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. |
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. |
||
< |
<syntaxhighlight lang="actionscript">$print("start\n") |
||
$goto(skip) |
$goto(skip) |
||
$print("Jumped over") |
$print("Jumped over") |
||
skip: |
skip: |
||
$print("end\n")</ |
$print("end\n")</syntaxhighlight> |
||
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. |
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,009: | Line 2,393: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Nim has exceptions and labelled breaks: |
Nim has exceptions and labelled breaks: |
||
< |
<syntaxhighlight lang="nim"> |
||
block outer: |
block outer: |
||
for i in 0..1000: |
for i in 0..1000: |
||
for j in 0..1000: |
for j in 0..1000: |
||
if i + j == 3: |
if i + j == 3: |
||
break outer</ |
break outer</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 2,026: | Line 2,410: | ||
Some portion of code can be restarted (as recursion) and skipped (as continuation). |
Some portion of code can be restarted (as recursion) and skipped (as continuation). |
||
< |
<syntaxhighlight lang="scheme"> |
||
; recursion: |
; recursion: |
||
(let loop ((n 10)) |
(let loop ((n 10)) |
||
Line 2,040: | Line 2,424: | ||
(print "ok.") |
(print "ok.") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Line 2,046: | Line 2,430: | ||
PARI inherits C's ability to <code>goto</code> or <code>longjmp</code>; the latter is used extensively in the library. |
PARI inherits C's ability to <code>goto</code> or <code>longjmp</code>; the latter is used extensively in the library. |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
label finish; |
|||
begin |
|||
var a := MatrRandomInteger(3,4); |
|||
var found := False; |
|||
for var i:=0 to a.RowCount-1 do |
|||
for var j:=0 to a.ColCount-1 do |
|||
if a[i,j] = 10 then |
|||
begin |
|||
found := True; |
|||
goto finish; |
|||
end; |
|||
finish: |
|||
Print(found); |
|||
end. |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="perl">sub outer { |
||
print "In outer, calling inner:\n"; |
print "In outer, calling inner:\n"; |
||
inner(); |
inner(); |
||
Line 2,083: | Line 2,486: | ||
print "\nCalling inner:\n"; |
print "\nCalling inner:\n"; |
||
inner(); # will die</ |
inner(); # will die</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Line 2,089: | Line 2,492: | ||
Using this 'baroque' syntax is viewed as an effective means of dissuading novices from adopting goto as a weapon of choice. |
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)--> |
Note that pwa/p2js does not support #ilASM{} at all. <!--(notonline)--> |
||
< |
<syntaxhighlight lang="phix">#ilASM{ jmp :%somelabel } |
||
... |
... |
||
#ilASM{ :%somelabel }</ |
#ilASM{ :%somelabel }</syntaxhighlight> |
||
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. |
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 |
Local labels are declared with a double colon (::) and referenced with a single colon |
||
< |
<syntaxhighlight lang="phix">#ilASM{ jmp :local |
||
... |
... |
||
::local }</ |
::local }</syntaxhighlight> |
||
They can only be referenced at the top level from within the same #ilASM construct, or anywhere within the routine where they are defined. |
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 |
Phix also supports anonymous local labels |
||
< |
<syntaxhighlight lang="phix">#ilASM{ jmp @f |
||
... |
... |
||
@@: |
@@: |
||
... |
... |
||
jle @b }</ |
jle @b }</syntaxhighlight> |
||
There are also optional (global) labels: |
There are also optional (global) labels: |
||
< |
<syntaxhighlight lang="phix">#ilASM{ call :!optlbl |
||
[32] |
[32] |
||
pop eax |
pop eax |
||
Line 2,119: | Line 2,522: | ||
push qword[rsp] |
push qword[rsp] |
||
[] |
[] |
||
ret }</ |
ret }</syntaxhighlight> |
||
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. |
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. |
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,127: | Line 2,530: | ||
Lastly (for completeness) there are init labels, defined using |
Lastly (for completeness) there are init labels, defined using |
||
<lang |
<syntaxhighlight lang="phix">#ilASM{ :>init }</syntaxhighlight> |
||
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. |
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,138: | Line 2,541: | ||
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": |
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": |
||
< |
<syntaxhighlight lang="picolisp">(de foo (N) |
||
(prinl "This is 'foo'") |
(prinl "This is 'foo'") |
||
(printsp N) |
(printsp N) |
||
(or (=0 (dec 'N)) (run (cddr foo))) )</ |
(or (=0 (dec 'N)) (run (cddr foo))) )</syntaxhighlight> |
||
Test: |
Test: |
||
<pre>: (foo 7) |
<pre>: (foo 7) |
||
Line 2,156: | Line 2,559: | ||
<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. |
<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. |
||
<lang |
<syntaxhighlight lang="pli">on conversion goto restart;</syntaxhighlight> |
||
=={{header|PL/SQL}}== |
=={{header|PL/SQL}}== |
||
PL/SQL supports both GOTOs and structured exception handling: |
PL/SQL supports both GOTOs and structured exception handling: |
||
< |
<syntaxhighlight lang="pl/sql">DECLARE |
||
i number := 5; |
i number := 5; |
||
divide_by_zero EXCEPTION; |
divide_by_zero EXCEPTION; |
||
Line 2,185: | Line 2,588: | ||
DBMS_OUTPUT.put_line( 'Finally' ); |
DBMS_OUTPUT.put_line( 'Finally' ); |
||
END; |
END; |
||
/</ |
/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>startLoop |
<pre>startLoop |
||
Line 2,201: | Line 2,604: | ||
current loop. The syntax for a label is as follows (this example shows a |
current loop. The syntax for a label is as follows (this example shows a |
||
label in a While loop): |
label in a While loop): |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
:myLabel while (<condition>) { <statement list>} |
:myLabel while (<condition>) { <statement list>} |
||
</syntaxhighlight> |
|||
</lang> |
|||
The label is a colon followed by a name that you assign. The label must be |
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 |
the first token in a statement, and it must be followed by the looping |
||
Line 2,217: | Line 2,620: | ||
This schematic example has a While statement with a For statement: |
This schematic example has a While statement with a For statement: |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
:myLabel while (<condition 1>) |
:myLabel while (<condition 1>) |
||
{ |
{ |
||
Line 2,227: | Line 2,630: | ||
} |
} |
||
$a = $c # A statement after the labeled While-loop |
$a = $c # A statement after the labeled While-loop |
||
</syntaxhighlight> |
|||
</lang> |
|||
If condition 2 evaluates to True, the execution of the script skips down |
If condition 2 evaluates to True, the execution of the script skips down |
||
Line 2,235: | Line 2,638: | ||
You can nest many labeled loops, as shown in the following schematic |
You can nest many labeled loops, as shown in the following schematic |
||
example. |
example. |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
:red while (<condition1>) |
:red while (<condition1>) |
||
{ |
{ |
||
Line 2,251: | Line 2,654: | ||
} |
} |
||
# After "red" loop |
# After "red" loop |
||
</syntaxhighlight> |
|||
</lang> |
|||
If the $b variable evaluates to True, execution of the script resumes |
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 |
after the loop that is labeled "red". If the $c variable evaluates to |
||
Line 2,264: | Line 2,667: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">OnErrorGoto(?ErrorHandler) |
||
OpenConsole() |
OpenConsole() |
||
Gosub label4 |
Gosub label4 |
||
Line 2,294: | Line 2,697: | ||
ErrorHandler: |
ErrorHandler: |
||
PrintN(ErrorMessage()) : Goto label4</ |
PrintN(ErrorMessage()) : Goto label4</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>eins zwei eins zwei eins zwei - drei -</pre> |
<pre>eins zwei eins zwei eins zwei - drei -</pre> |
||
Line 2,302: | Line 2,705: | ||
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: |
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: |
# Example 2: Restarting a loop: |
||
from goto import goto, label |
from goto import goto, label |
||
Line 2,316: | Line 2,719: | ||
goto .start |
goto .start |
||
print output, "\n" |
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. |
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,324: | Line 2,727: | ||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
{{works with|Yabasic}} |
{{works with|Yabasic}} |
||
< |
<syntaxhighlight lang="qbasic"> |
||
PRINT "First line." |
PRINT "First line." |
||
GOSUB sub1 |
GOSUB sub1 |
||
Line 2,346: | Line 2,749: | ||
Finished: |
Finished: |
||
PRINT "... with goto and gosub, thankfully." |
PRINT "... with goto and gosub, thankfully." |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Igual que la entrada de FutureBasic.</pre> |
<pre>Igual que la entrada de FutureBasic.</pre> |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
<syntaxhighlight lang="qb64"> |
|||
<lang QB64> |
|||
' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic |
' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic |
||
' here a GOTO demo of loops FOR-NEXT and WHILE-WEND |
' here a GOTO demo of loops FOR-NEXT and WHILE-WEND |
||
Line 2,394: | Line 2,797: | ||
Q = Q + 1 |
Q = Q + 1 |
||
GoTo 2 |
GoTo 2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 2,416: | Line 2,819: | ||
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. |
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[ 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. |
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. |
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. |
||
< |
<syntaxhighlight lang="quackery"> [ ]'[ ]do[ ' ]else[ swap of ]do[ ] is jump-into ( n --> ) |
||
5 jump-into |
5 jump-into |
||
Line 2,426: | Line 2,829: | ||
( 0 1 2 3 4 offsets of each item ) |
( 0 1 2 3 4 offsets of each item ) |
||
( 5 6 7 8 9 from start of nest ) |
( 5 6 7 8 9 from start of nest ) |
||
2 echo 3 echo again ]</ |
2 echo 3 echo again ]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,436: | Line 2,839: | ||
As a little example: |
As a little example: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (never-divides-by-zero return) |
(define (never-divides-by-zero return) |
||
(displayln "I'm here") |
(displayln "I'm here") |
||
Line 2,448: | Line 2,851: | ||
; I'm here |
; I'm here |
||
; "Leaving" (because that's what the function returns) |
; "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. |
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,455: | Line 2,858: | ||
Where we generate elements of a list one at a time: |
Where we generate elements of a list one at a time: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end-off-the-list) |
;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end-off-the-list) |
||
(define (generate-one-element-at-a-time a-list) |
(define (generate-one-element-at-a-time a-list) |
||
Line 2,476: | Line 2,879: | ||
;; time to return the generator |
;; time to return the generator |
||
generator) |
generator) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Relation}}== |
=={{header|Relation}}== |
||
Line 2,485: | Line 2,888: | ||
Retro allows the user to jump to any address. |
Retro allows the user to jump to any address. |
||
< |
<syntaxhighlight lang="retro">:foo #19 &n:inc \ju...... #21 ;</syntaxhighlight> |
||
When executed, the stack will contain 20; control does not return to the '''foo''' function. |
When executed, the stack will contain 20; control does not return to the '''foo''' function. |
||
Line 2,493: | Line 2,896: | ||
===Label-based jumps=== |
===Label-based jumps=== |
||
<lang |
<syntaxhighlight lang="raku" line> outer-loop: loop { |
||
inner-loop: loop { |
inner-loop: loop { |
||
# NYI # goto inner-loop if rand > 0.5; # Hard goto |
# NYI # goto inner-loop if rand > 0.5; # Hard goto |
||
Line 2,505: | Line 2,908: | ||
LEAVE { say "Leaving outer loop block" } |
LEAVE { say "Leaving outer loop block" } |
||
LAST { say "Ending outer loop" } |
LAST { say "Ending outer loop" } |
||
}</ |
}</syntaxhighlight> |
||
Produces random output, but here's a representative run: |
Produces random output, but here's a representative run: |
||
Line 2,521: | Line 2,924: | ||
Continuations in Raku are currently limited to use in generators via the gather/take model: |
Continuations in Raku are currently limited to use in generators via the gather/take model: |
||
<lang |
<syntaxhighlight lang="raku" line> my @list = lazy gather for ^100 -> $i { |
||
if $i.is-prime { |
if $i.is-prime { |
||
say "Taking prime $i"; |
say "Taking prime $i"; |
||
Line 2,528: | Line 2,931: | ||
} |
} |
||
say @list[5];</ |
say @list[5];</syntaxhighlight> |
||
This outputs: |
This outputs: |
||
Line 2,544: | Line 2,947: | ||
Exceptions are fairly typical in Raku: |
Exceptions are fairly typical in Raku: |
||
<lang |
<syntaxhighlight lang="raku" line> die "This is a generic, untyped exception";</syntaxhighlight> |
||
Will walk up the stack until either some `CATCH` block intercepts the specific exception type or we exit the program. |
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. |
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. |
||
<lang |
<syntaxhighlight lang="raku" line> sub foo() { fail "oops" } |
||
my $failure = foo; |
my $failure = foo; |
||
say "Called foo"; |
say "Called foo"; |
||
say "foo not true" unless $failure; |
say "foo not true" unless $failure; |
||
say "foo not defined" unless $failure.defined; |
say "foo not defined" unless $failure.defined; |
||
say "incremented foo" if $failure++; # exception</ |
say "incremented foo" if $failure++; # exception</syntaxhighlight> |
||
Produces: |
Produces: |
||
Line 2,567: | Line 2,970: | ||
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). |
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). |
||
<lang |
<syntaxhighlight lang="raku" line> sub foo($i) { |
||
if $i == 0 { |
if $i == 0 { |
||
die "Are you sure you want /0?"; |
die "Are you sure you want /0?"; |
||
Line 2,581: | Line 2,984: | ||
CATCH { |
CATCH { |
||
when ~$_ ~~ m:s/Are you sure/ { .resume; #`(yes, I'm sure) } |
when ~$_ ~~ m:s/Are you sure/ { .resume; #`(yes, I'm sure) } |
||
}</ |
}</syntaxhighlight> |
||
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: |
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,598: | Line 3,001: | ||
<br>as long as the '''END''' or the '''DO''' loop isn't executed. |
<br>as long as the '''END''' or the '''DO''' loop isn't executed. |
||
<br>The following used PC/REXX to illustrate this example. |
<br>The following used PC/REXX to illustrate this example. |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm demonstrates various jumps (GOTOs). In REXX, it's a SIGNAL. */ |
||
say 'starting...' |
say 'starting...' |
||
signal aJump |
signal aJump |
||
Line 2,616: | Line 3,019: | ||
cJump: say 'and here we are at cJump.' |
cJump: say 'and here we are at cJump.' |
||
exit |
exit |
||
end /*k*/</ |
end /*k*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,643: | Line 3,046: | ||
As mentioned above some implementations may have restrictions on that. |
As mentioned above some implementations may have restrictions on that. |
||
This Signal jumps into a Do loop inside a Procedure: |
This Signal jumps into a Do loop inside a Procedure: |
||
< |
<syntaxhighlight lang="rexx">i=13 |
||
signal label |
signal label |
||
say 'This is never executed' |
say 'This is never executed' |
||
Line 2,653: | Line 3,056: | ||
End |
End |
||
Return |
Return |
||
real_start:</ |
real_start:</syntaxhighlight> |
||
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. |
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 |
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: |
An example: |
||
< |
<syntaxhighlight lang="rexx">/* REXX *************************************************************** |
||
* 12.12.2012 Walter Pachl |
* 12.12.2012 Walter Pachl |
||
**********************************************************************/ |
**********************************************************************/ |
||
Line 2,674: | Line 3,077: | ||
Say 'argument must be a or b or omitted' |
Say 'argument must be a or b or omitted' |
||
Exit |
Exit |
||
eoj: say 'here we could print statistics'</ |
eoj: say 'here we could print statistics'</syntaxhighlight> |
||
This can be useful when the different parts of the program span a few pages. |
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. |
Also a Signal eoj in order to Exit from any point in the program to some final activities can be useful. |
||
Line 2,686: | Line 3,089: | ||
====Simple==== |
====Simple==== |
||
A simple example of labels and goto: |
A simple example of labels and goto: |
||
< |
<syntaxhighlight lang="robotic"> |
||
. "The label 'touch' is used to let the player touch the robot" |
. "The label 'touch' is used to let the player touch the robot" |
||
. "to execute the following" |
. "to execute the following" |
||
Line 2,700: | Line 3,103: | ||
* "Label B was reached" |
* "Label B was reached" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
It prints "Label B was reached", skipping "label_a" entirely. |
It prints "Label B was reached", skipping "label_a" entirely. |
||
Line 2,706: | Line 3,109: | ||
====Conditional==== |
====Conditional==== |
||
This will jump to a given label, depending on the condition of "local1": |
This will jump to a given label, depending on the condition of "local1": |
||
< |
<syntaxhighlight lang="robotic"> |
||
set "local1" to 2 |
set "local1" to 2 |
||
end |
end |
||
Line 2,721: | Line 3,124: | ||
* "Label B was reached" |
* "Label B was reached" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Since "local1" equals 2, it prints "Label B was reached". |
Since "local1" equals 2, it prints "Label B was reached". |
||
Line 2,728: | Line 3,131: | ||
When you goto a label, it chooses the top-most label name in the code. |
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: |
However, with the use of "zap" and "restore", we can use the same label name multiple times in our code: |
||
< |
<syntaxhighlight lang="robotic"> |
||
end |
end |
||
: "touch" |
: "touch" |
||
Line 2,742: | Line 3,145: | ||
restore "label_a" 1 |
restore "label_a" 1 |
||
end |
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. |
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,749: | Line 3,152: | ||
With subroutines, we can jump to a given label and come back to where we left off after we called the inital "goto" statement. |
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 (#): |
To use these, the labels and the string supplied in the "goto" statements must have a number sign (#): |
||
< |
<syntaxhighlight lang="robotic"> |
||
. "The 'wait' statements are used to demonstrate what is happening" |
. "The 'wait' statements are used to demonstrate what is happening" |
||
set "local1" to 1 |
set "local1" to 1 |
||
Line 2,779: | Line 3,182: | ||
* "Label D was reached" |
* "Label D was reached" |
||
goto "#top" |
goto "#top" |
||
</syntaxhighlight> |
|||
</lang> |
|||
The following is printed out in order: |
The following is printed out in order: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
Label A was reached |
Label A was reached |
||
Done with Label A |
Done with Label A |
||
Line 2,788: | Line 3,191: | ||
Label D was reached |
Label D was reached |
||
Skipped finishing Label B and C |
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"). |
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,797: | Line 3,200: | ||
The next example abuses a continuation to solve [[FizzBuzz#Ruby]]. It is slower and more confusing than an ordinary loop. |
The next example abuses a continuation to solve [[FizzBuzz#Ruby]]. It is slower and more confusing than an ordinary loop. |
||
{{libheader|continuation}} |
{{libheader|continuation}} |
||
< |
<syntaxhighlight lang="ruby">require 'continuation' unless defined? Continuation |
||
if a = callcc { |c| [c, 1] } |
if a = callcc { |c| [c, 1] } |
||
Line 2,818: | Line 3,221: | ||
puts |
puts |
||
c[c, i + 1] |
c[c, i + 1] |
||
end</ |
end</syntaxhighlight> |
||
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. |
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| |
=={{header|SNOBOL4}}== |
||
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}}== |
=={{header|SPL}}== |
||
In SPL jumps can be non-conditional and conditional. |
In SPL jumps can be non-conditional and conditional. |
||
This is an example of non-conditional jump to label "myLabel": |
This is an example of non-conditional jump to label "myLabel": |
||
< |
<syntaxhighlight lang="spl">myLabel -> |
||
... |
... |
||
:myLabel</ |
:myLabel</syntaxhighlight> |
||
This is an example of conditional jump to label "4", which is done if a=0: |
This is an example of conditional jump to label "4", which is done if a=0: |
||
< |
<syntaxhighlight lang="spl">4 -> a=0 |
||
... |
... |
||
:4</ |
:4</syntaxhighlight> |
||
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. |
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": |
This is an example of visiting label "label 55": |
||
< |
<syntaxhighlight lang="spl">label 55 <-> |
||
#.output("1") |
#.output("1") |
||
:label 55 |
:label 55 |
||
#.output("2") |
#.output("2") |
||
<-</ |
<-</syntaxhighlight> |
||
and output is: |
and output is: |
||
{{out}} |
{{out}} |
||
Line 2,852: | Line 3,313: | ||
=={{header|SSEM}}== |
=={{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: |
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: |
||
< |
<syntaxhighlight lang="ssem">10000000000000000000000000000000 0. 1 to CI |
||
11001000000000000000000000000000 1. 19</ |
11001000000000000000000000000000 1. 19</syntaxhighlight> |
||
and this accomplishes a relative jump forward by five words: |
and this accomplishes a relative jump forward by five words: |
||
< |
<syntaxhighlight lang="ssem">10000000000001000000000000000000 0. Add 1 to CI |
||
00100000000000000000000000000000 1. 4</ |
00100000000000000000000000000000 1. 4</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{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. |
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}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Public Sub jump() |
||
Debug.Print "VBA only allows" |
Debug.Print "VBA only allows" |
||
GoTo 1 |
GoTo 1 |
||
Line 2,880: | Line 3,402: | ||
two: |
two: |
||
Debug.Print "On <n> GoSub let you jump to the n-th label": Return |
Debug.Print "On <n> GoSub let you jump to the n-th label": Return |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre>VBA only allows |
<pre>VBA only allows |
||
jumps in procedures with GoTo |
jumps in procedures with GoTo |
||
Line 2,892: | Line 3,414: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
In VBScript, there is no <code>goto</code> statement. It is a good thing for structured programming. |
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}}== |
=={{header|VTL-2}}== |
||
Line 2,901: | Line 3,459: | ||
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> |
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> |
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> |
||
< |
<syntaxhighlight lang="vtl2">1010 ?="@1010: Where to goto? "; |
||
1020 #=? |
1020 #=? |
||
1030 ?="@1030" |
1030 ?="@1030" |
||
Line 2,908: | Line 3,466: | ||
1060 #=1010 |
1060 #=1010 |
||
2000 ?="@2000" |
2000 ?="@2000" |
||
2010 ?="Exiting..."</ |
2010 ?="Exiting..."</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,937: | Line 3,495: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="wren">var func = Fn.new { |
||
for (i in 1..10) { |
for (i in 1..10) { |
||
if (i == 1) continue // jumps to next iteration when 'i' equals 1 |
if (i == 1) continue // jumps to next iteration when 'i' equals 1 |
||
Line 2,960: | Line 3,518: | ||
System.print("yielding") |
System.print("yielding") |
||
fiber.call() // resumes the fiber |
fiber.call() // resumes the fiber |
||
return // would exit the module (and script) without error but won't be reached</ |
return // would exit the module (and script) without error but won't be reached</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,975: | Line 3,533: | ||
resuming |
resuming |
||
aborting |
aborting |
||
[./ |
[./Jump_anywhere line 17] in new(_) block argument |
||
</pre> |
</pre> |
||
Line 3,003: | Line 3,561: | ||
{{works with|QBasic}} |
{{works with|QBasic}} |
||
{{works with|BASIC256}} |
{{works with|BASIC256}} |
||
< |
<syntaxhighlight lang="freebasic">print "First line." |
||
gosub sub1 |
gosub sub1 |
||
print "Fifth line." |
print "Fifth line." |
||
Line 3,024: | Line 3,582: | ||
Finished: |
Finished: |
||
print "... with goto and gosub, thankfully." |
print "... with goto and gosub, thankfully." |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Igual que la entrada de FutureBasic.</pre> |
<pre>Igual que la entrada de FutureBasic.</pre> |
||
Line 3,038: | Line 3,596: | ||
<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. |
<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. |
||
< |
<syntaxhighlight lang="z80">and &01 ;returns 0 if the accumulator is even and 1 if odd. Also sets the zero flag accordingly. |
||
jr z,SkipOddCode |
jr z,SkipOddCode |
||
;whatever you want to do when the accumulator is odd goes here, but it must be 127 bytes or fewer. |
;whatever you want to do when the accumulator is odd goes here, but it must be 127 bytes or fewer. |
||
SkipOddCode: |
SkipOddCode: |
||
;rest of program</ |
;rest of program</syntaxhighlight> |
||
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]]. |
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]]. |
||
< |
<syntaxhighlight lang="z80">ld b,25 |
||
loop: |
loop: |
||
djnz loop ;loop 25 times.</ |
djnz loop ;loop 25 times.</syntaxhighlight> |
||
Line 3,057: | Line 3,615: | ||
<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. |
<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. |
||
< |
<syntaxhighlight 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. |
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. |
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") |
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.)</ |
;(Unlike the others, JR cannot jump based on the sign flag or parity/overflow flag.)</syntaxhighlight> |
||
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. |
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,070: | Line 3,628: | ||
<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>. |
<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>. |
||
< |
<syntaxhighlight lang="z80"> |
||
ld hl,foo ;rather than directly specifying "foo", you would normally retrieve it by indexing a table. |
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. |
;This was done only to keep the example as simple as possible. |
||
Line 3,085: | Line 3,643: | ||
foo: |
foo: |
||
ld a,0 |
ld a,0 |
||
ret</ |
ret</syntaxhighlight> |
||
''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.'' |
''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,106: | Line 3,664: | ||
{{omit from|Oberon-2}} |
{{omit from|Oberon-2}} |
||
{{omit from|UNIX Shell|Does not have goto or line labels, but can break from nested loops}} |
{{omit from|UNIX Shell|Does not have goto or line labels, but can break from nested loops}} |
||
{{omit from|Insitux}} |
Revision as of 17:51, 18 June 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their conditional structures and loops to local jumps within a function. Some assembly languages limit certain jumps or branches to a small range.
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like Exceptions or Generator. This task provides a "grab bag" for several types of jumps. There are non-local jumps across function calls, or long jumps to anywhere within a program. Anywhere means not only to the tops of functions!
- Some languages can go to any global label in a program.
- Some languages can break multiple function calls, also known as unwinding the call stack.
- Some languages can save a continuation. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).
These jumps are not all alike.
A simple goto never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.
- Task
Use your language to demonstrate the various types of jumps that it supports.
Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like Exceptions or Generator.
360 Assembly
The unconditionnal branch instruction B is the jump anywhere of the S/360 assembler.
...
B ANYWHERE branch
...
ANYWHERE EQU * label
...
6502 Assembly
Assembly languages in general do not restrict where or how you can jump. 6502 Assembly in particular does not have any sort of W^X protection so the entire address space is a valid jump target. The question is, what address does your code reside in after it is assembled? Most assemblers allow you to define labels, which get converted to the address of the instruction just after the label. This way you don't have to manually calculate the address yourself.
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)
JMP PrintChar ; jump to the label "PrintChar" where a routine to print a letter to the screen is located.
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:
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
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:
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
lda JumpTable_Lo,x
sta $10
lda JumpTable_Hi,x
sta $11
JMP ($0010)
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.
Another way to do this is with a "jump block."
.org $8000
JMP PrintChar
JMP WaitChar
JMP ReadKeys
JMP MoveMouse
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.
lda $80
sta $21
txa
clc
adc #$03
sta $20
JMP ($0020)
If X was 0, the JMP takes us to WaitChar.
If X was 3, the JMP takes us to ReadKeys.
If X was 6, the JMP takes us to MoveMouse.
If X isn't a multiple of 3, or is too large, the JMP will take you... somewhere. This isn't good, so make sure you have a way to bounds check.
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.
JumpTable:
word PrintChar
word PrintString
word MoveMouse
ldx #$02
JMP (JumpTable,x) ;dereferences to JMP PrintString
Your index needs to be a multiple of 2 for this to work, most of the time you'll use ASL A
then TAX
to double your index prior to performing the indirect jump.
Indirect JSR
Make sure you read Indirect Jump before reading this, it won't make much sense otherwise.
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.
ReturnTable: dw PrintChar-1,WaitChar-1,ReadKeys-1,MoveMouse-1
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.
;execution is currently here
JSR UseReturnTable ;the address just after this label is pushed onto the stack.
;the chosen subroutine's RTS will bring you here.
UseReturnTable: ;pretend this is somewhere far away from where execution is, its distance doesn't matter.
ASL ;double the value of the variable, because this is a table of words.
TAX
LDA ReturnTable+1,x ;load the chosen subroutine's high byte into the accumulator
PHA ;push it onto the stack
LDA ReturnTable,x ;load the chosen subroutine's low byte into the accumulator
PHA ;push it onto the stack.
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.
Now all of that was a bit confusing wasn't it? Essentially this "abuses" the following concepts:
- The JSR instruction automatically pushes the current address + 1 onto the stack.
- The RTS instruction pulls the top two bytes off the stack, subtracts 1 from the low byte, and sets the program counter to that value.
Finally, and most importantly:
- The RTS instruction assumes that the top two bytes of the stack are the correct place to return to, and goes there without any way of knowing if the address is "correct."
With this knowledge in mind, we can take a value equal to the address of the desired subroutine, minus 1, push it onto the stack, then "return" to that subroutine (even if we've never been there!)
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. JSR ($####,x)
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 JMP
on the 65816 is confined to $nn0000-$nnFFFF
. To break free of this limitation, you'll need to use JML $xxxxxx
to go to a different bank. JSL $xxxxxx
can call a subroutine in a different bank, and you'll need to use RTL
to safely return from a JSL
.
68000 Assembly
Local Jumps
The 68000's branching syntax is nearly identical to that of the 6502. One key difference is that after a comparison, carry set is less than, and carry clear is greater than or equal. Thankfully, the equivalent BGE
and BLT
can take the place of BCC
and BCS
for unsigned comparisons, respectively, which makes the code easier to read.
In addition, for nearby subroutines,BSR
can be used in place ofJSR
to save data. There is alsoBRA
(branch always) for unconditional local jumping, which the original 6502 didn't have.
bra foo
nop ;execution will never reach here
foo:
CMP.L D0,D1
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:
Absolute Jumps
The 68000 has JMP
and JSR
for absolute jumping and function calls, respectively. When you JSR
, the next RTS
you encounter will return the program counter to just after the JSR
statement you came from, provided that the return address is still on top of the stack when the RTS
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:
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.
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 RET
and trampoline. RET
is called RTS
on the 6502 and 68000)
;For this example, we want to execute "ReadJoystick"
MOVE.W D0,#1
JSR Retpoline
;;;;; ReadJoystick's RTS will return the program counter to here
; rest of program
;assume this is somewhere far away from the JSR above, and that execution won't fall through to here.
Retpoline: ;uses D0 as the index into the table.
LEA A0,SubroutineTable
LSL.B #2,D0 ;multiply D0 by 4 since this is a table of 32-bit memory addresses
MOVE.L (A0,D0),A0 ;offset and deference A0, now A0 contains the address of ReadJoystick
PEA A0 ;push the address of A0 onto the stack
RTS ;now we'll "return" to ReadJoystick. If it ends in an RTS, that RTS shall return to the area specified above.
SubroutineTable:
DC.L MoveMouse, DC.L ReadJoystick, DC.L ReadKeyboard, DC.L PrintString
Indirect Jumps
In addition to a fixed memory address, you can also JMP
to the value stored in an address register (effectively MOVE.L An,PC
if such a thing existed), or you can dereference the pointer stored in an address register and jump to that instead.
8086 Assembly
The 8086 has the unconditional JMP
, as well as conditional variants JZ
,JNZ
, etc. There are also a few special jump types:
JCXZ
will jump only if the CX
register equals 0. This is useful for skipping a loop if CX
(the loop counter) is already zero.
JCXZ bar
foo:
LOOP foo ;subtract 1 from CX, and if CX is still nonzero jump back to foo
bar:
LOOP label
is the equivalent of DEC CX JNZ label
and, as the name implies, is used for looping. You might have heard that DEC CX JNZ label
should always be used over LOOP label
for better performance. This is only true on later x86-based CPUs - the reasons for LOOP
's poor performance weren't present on the 8086, and as such it's better to use there.
Although JMP
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 JMP
or CALL
cannot exit that segment.
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"
- Output:
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.
Ada
procedure Goto_Test is
begin
Stuff;
goto The_Mother_Ship; -- You can do this if you really must!
Stuff;
if condition then
Stuff;
<<Jail>>
Stuff;
end if;
Stuff;
-- Ada does not permit any of the following
goto Jail;
goto The_Sewer;
goto The_Morgue;
Stuff;
case condition is
when Arm1 =>
Stuff;
goto The_Gutter; -- Cant do this either
Stuff;
when Arm2 =>
Stuff;
<<The_Gutter>>
Stuff;
<<The_Sewer>>
Stuff;
end case;
Stuff;
for I in Something'Range loop
Stuff;
<<The_Morgue>>
if You_Are_In_Trouble then
goto The_Mother_Ship;
-- This is the usual use of a goto.
end if;
Stuff;
end loop;
Stuff;
<<The_Mother_Ship>>
Stuff;
end Goto_Test;
ARM Assembly
The ARM's branching syntax is similar to the 6502 and the 68000. Branches can be given a condition, and if the condition is not met no jump will take place, and execution simply "falls through" to the instruction below.
B
is an unconditional branch. The operand is a specified label, which the assembler will calculate the necessary offset to adjust the program counter (PC/R15
) by. Branches have a limit on how far forward or back you can go (on ARM v4 it was 4096 bytes) but this limit is incredibly generous so you're not likely to encounter it.
- Like most instructions, a condition code can be added to a branch. The zero, carry, and overflow flags can all be used to branch.
BL
will branch to the specified label, and willMOV LR,PC
before the branch. This is the equivalent ofCALL
on x86 Assembly. Nested subroutines will require that the link register is caller-preserved so that once the inner subroutine returns, the outer one knows where to return to. Returning from a subroutine can be done withBX LR
orMOV PC,LR
. (The former is preferred because it can switch to THUMB mode and back, which will be explained next.)
BX
takes another register as its operand and will setPC
to that register's value. In addition, if the least significant digit of the register's value is 1, the CPU will enter THUMB mode, which uses a more limited instruction set, but each instruction only takes up 16 bits instead of 32. This is often used to save memory when writing firmware for embedded systems. To switch back to 32-bit ARM mode, you'll need to useBX
again, with a register whose value is a multiple of 4. In addition,BLX
(a combination ofBL
andBX
) can also be used.
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 PC
that isn't a multiple of 4 will crash the CPU.
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
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 LR
and pop PC
.
PUSH {R0-R12,LR}
POP {R0-R12,PC}
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
STMFD sp!,{r0-r12,lr}
LDMFD sp!,{r0-r12,pc}
Arturo
Arturo has no GOTO equivalent and no labels.
Apart from exceptions handling (with try and try?), Arturo has continue (to continue to next iteration - within a loop) and break (to leave a loop).
AutoHotkey
; Define a function.
function()
{
MsgBox, Start
gosub jump
free:
MsgBox, Success
}
; Call the function.
function()
goto next
return
jump:
MsgBox, Suspended
return
next:
Loop, 3
{
gosub jump
}
return
/*
Output (in Message Box):
Start
Suspended
Success
Suspended
Suspended
Suspended
*/
BASIC
10 GOTO 100: REM jump to a specific line
20 RUN 200: REM start the program running from a specific line
Some versions of basic allow line labels to be used. Here we jump to a label:
GOTO mylabel
Applesoft BASIC
caveat: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html
0 REM GOTO
100 GOTO 110 : REM JUMP TO A SPECIFIC LINE
110 RUN 120 : REM START THE PROGRAM RUNNING FROM A SPECIFIC LINE
120 IF 1 GOTO 130 : REM CONDITIONAL JUMP
130 IF 1 THEN 140 : REM THEN ALSO WORKS IN PLACE OF GOTO
140 IF 1 THEN GOTO 150 : REM BE VERBOSE BY USING THEN GOTO
150 ON A GOTO 170, 180, 190 : REM JUMP A SPECIFIC LINE NUMBER IN THE LIST INDEXED BY THE VALUE OF A STARTING AT 1, IF A IS OUT OF RANGE DO NOT JUMP
160 ON ERR GOTO 270 : REM WHEN AN ERROR OCCURS JUMP TO A SPECIFIC LINE
170 GOSUB 180 : REM JUMP TO LINE 180, PUSHING THE CURRENT PLACE ON THE STACK
180 POP : REM POP THE CURRENT PLACE FROM THE STACK, EFFECTIVELY MAKING THE PREVIOUS LINE A JUMP
190 CALL -151 : REM CALL ANY MACHINE LANGUAGE SUBROUTINE, IT MIGHT RETURN, IT MIGHT NOT
200 & : REM CALL THE USER-DEFINED AMPERSAND ROUTINE, IT MIGHT RETURN, IT MIGHT NOT
210 ? USR(0) : REM CALL THE USER-DEFINED FUNCTION, IT MIGHT RETURN, IT MIGHT NOT
220 S = 6 : ?CHR$(4)"PR#"S : REM CALL THE ROM ROUTINE IN SLOT S
230 S = 6 : ?CHR$(4)"IN#"S : REM CALL THE ROM ROUTINE IN SLOT S
240 ?CHR$(4)"RUN PROGRAM" : REM RUN A BASIC PROGRAM FROM DISK
250 ?CHR$(4)"BRUN BINARY PROGRAM": REM RUN A MACHINE LANGUAGE BINARY PROGRAM FROM DISK
260 ?CHR$(4)"EXEC PROGRAM.EX" : REM EXECUTE THE TEXT THAT IS CONTAINED IN THE FILE PROGRAM.EX
270 RESUME : REM JUMP BACK TO THE STATEMENT THAT CAUSED THE ERROR
280 STOP : REM BREAK THE PROGRAM
290 END : REM END THE PROGRAM
300 GOTO : REM NO LINE NUMBER, JUMPS TO LINE 0
CONT : REM CONTINUE, JUMP BACK TO WHERE THE PROGRAM STOPPED
BASIC256
BASIC256 supports both goto
and gosub
.
print "First line."
gosub sub1
print "Fifth line."
goto Ending
sub1:
print "Second line."
gosub sub2
print "Fourth line."
return
Ending:
print "We're just about done..."
goto Finished
sub2:
print "Third line."
return
Finished:
print "... with goto and gosub, thankfully."
end
- Output:
Igual que la entrada de FutureBasic.
Chipmunk Basic
Chipmunk Basic supports both goto
and gosub
.
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
- Output:
Same as FutureBasic entry.
GW-BASIC
GW-BASIC supports both goto
and gosub
.
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
IS-BASIC
10 GOTO 100 ! jump to a specific line
20 RUN 200 ! start the program running from a specific line
Minimal BASIC
The GW-BASIC solution works without any changes.
MSX Basic
The GW-BASIC solution works without any changes.
Quite BASIC
The GW-BASIC solution works without any changes.
Run BASIC
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"
True BASIC
True BASIC supports both goto
and gosub
.
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
- Output:
Same as FutureBasic entry.
Tiny BASIC
The GW-BASIC solution works without any changes.
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.
{ 0 ? "Will not execute"; "Will execute" }
"Will execute"
Function calls
You can call a function from a block, temporarily jumping over to the function's body, and coming back.
F←{𝕩⊣•Out"In Second"}
{
•Out "First"
F@
•Out "Last"
}
First
In Second
Last
C
C has goto LABEL
keyword.
if (x > 0) goto positive;
else goto negative;
positive:
printf("pos\n"); goto both;
negative:
printf("neg\n");
both:
...
The label must be literal, not computed at run time. This won't work:
goto (x > 0 ? positive : negative);
You can goto
almost anywhere inside the same function, but can't go across function boundaries. It's sometimes used to break out of nested loops:
for (i = 0; ...) {
for (j = 0; ...) {
if (condition_met) goto finish;
}
}
although you can (not that you should) jump into a loop, too:
goto danger;
for (i = 0; i < 10; i++) {
danger: /* unless you jumped here with i set to a proper value */
printf("%d\n", i);
}
For unwrapping call stack and go back up to a caller, see longjmp example; more powerful, but more expensive and complicated, is POSIX ucontext. The best application for goto is error handling, this simplifies the resource clean up of a large function. This is used in the linux kernel.
char *str;
int *array;
FILE *fp;
str = (char *) malloc(100);
if(str == NULL) {
return;
}
fp=fopen("c:\\test.csv", "r");
if(fp== NULL) {
free(str );
return;
}
array = (int *) malloc(15);
if(array==NULL) if(fp== NULL) {
free(str );
fclose(fp);
return;
}
...// read in the csv file and convert to integers
char *str;
int *array;
FILE *fp;
str = (char *) malloc(100);
if(str == NULL)
goto: exit;
fp=fopen("c:\\test.csv", "r");
if(fp== NULL)
goto: clean_up_str;
array = (int *) malloc(15);
if(array==NULL)
goto: clean_up_file;
...// read in the csv file and convert to integers
clean_up_array:
free(array);
clean_up_file:
fclose(fp);
clean_up_str:
free(str );
exit:
return;
C#
Like C, C# also has a goto LABEL
keyword. This section is partly copied from the section on C, since both languages share common syntax.
if (x > 0) goto positive;
else goto negative;
positive:
Console.WriteLine("pos\n"); goto both;
negative:
Console.WriteLine("neg\n");
both:
...
The label must be literal, not computed at run time. This won't work:
goto (x > 0 ? positive : negative);
You can goto
almost anywhere inside the same method, but can't go across method boundaries. It's sometimes used to break out of nested loops:
for (i = 0; ...) {
for (j = 0; ...) {
if (condition_met) goto finish;
}
}
The label must be in scope, so you cannot jump into a loop. This will not compile:
goto danger;
for (i = 0; i < 10; i++) {
danger:
Console.WriteLine(i);
}
In C#, you can also goto
a label from within any section of a try .. catch block. However, it is not permitted to jump out of a finally block.
int i = 0;
tryAgain:
try {
i++;
if (i < 10) goto tryAgain;
}
catch {
goto tryAgain;
}
finally {
//goto end; //Error
}
Another usage of goto
is to jump between case
labels inside a switch
statement:
public int M(int n) {
int result = 0;
switch (n) {
case 1:
cost += 25;
break;
case 2:
cost += 25;
goto case 1;
case 3:
cost += 50;
goto case 1;
}
return result;
}
C++
Like C, C++ also has a goto LABEL
statement which can be used to jump within a function.
#include <iostream>
#include <utility>
using namespace std;
int main(void)
{
cout << "Find a solution to i = 2 * j - 7\n";
pair<int, int> answer;
for(int i = 0; true; i++)
{
for(int j = 0; j < i; j++)
{
if( i == 2 * j - 7)
{
// use brute force and run until a solution is found
answer = make_pair(i, j);
goto loopexit;
}
}
}
loopexit:
cout << answer.first << " = 2 * " << answer.second << " - 7\n\n";
// jumping out of nested loops is the main usage of goto in
// C++. goto can be used in other places but there is usually
// a better construct. goto is not allowed to jump across
// initialized variables which limits where it can be used.
// this is case where C++ is more restrictive than C.
goto spagetti;
int k;
k = 9; // this is assignment, can be jumped over
/* The line below won't compile because a goto is not allowed
* to jump over an initialized value.
int j = 9;
*/
spagetti:
cout << "k = " << k << "\n"; // k was never initialized, accessing it is undefined behavior
}
- Output:
Find a solution to i = 2 * j - 7 9 = 2 * 8 - 7 k = 0
C++ also inherited std::longjmp from C which can jump out of functions but it is almost never used. See the C longjmp example.
Clipper
Clipper has no labels and goto statements. The exit statements allows leave the current loop and doesn't contain any label where to go.
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. jumps-program.
* Nobody writes like this, of course; but...
PROCEDURE DIVISION.
* You can jump anywhere you like.
start-paragraph.
GO TO an-arbitrary-paragraph.
yet-another-paragraph.
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 start-paragraph.
* But bear in mind: once you get there, the GO TO no longer goes to
* where it says it goes to.
a-paragraph-somewhere.
DISPLAY 'Never heard of him.'
STOP RUN.
some-other-paragraph.
* You think that's bad? You ain't seen nothing.
GO TO yet-another-paragraph.
an-arbitrary-paragraph.
DISPLAY 'Edsger who now?'
GO TO some-other-paragraph.
END PROGRAM jumps-program.
- Output:
Edsger who now? Never heard of him.
COBOL also supports computed go to phrases, given a list of labels (paragraph names) and an integer index into that list.
DATA DIVISION.
WORKING-STORAGE SECTION.
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'.
Common Lisp
In Common Lisp you can jump anywhere inside a tagbody.
(tagbody
beginning
(format t "I am in the beginning~%")
(sleep 1)
(go end)
middle
(format t "I am in the middle~%")
(sleep 1)
(go beginning)
end
(format t "I am in the end~%")
(sleep 1)
(go middle))
- Output:
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 ...
Computer/zero Assembly
A JMP (jump) instruction can transfer control to any point in memory. Its target can be modified at run time, if required, by using instruction arithmetic:
LDA goto
SUB somewhere
ADD somewhereElse
STA goto
goto: JMP somewhere
By the time execution reaches the instruction labelled goto, that instruction has become JMP somewhereElse. (This kind of coding does not, however, necessarily make the flow of control easier to follow.)
D
Apart from exception handling, D has the break and continue statements that can jump to a label in the current scope. The goto statement can jump to any label inside the current function.
DCL
$ return ! ignored since we haven't done a gosub yet
$
$ if p1 .eqs. "" then $ goto main
$ inner:
$ exit
$
$ main:
$ goto label ! if label hasn't been read yet then DCL will read forward to find label
$ label:
$ write sys$output "after first occurrence of label"
$
$ on control_y then $ goto continue1 ! we will use this to get out of the loop that's coming up
$
$ label: ! duplicate labels *are* allowed, the most recently read is the one that will be the target
$ write sys$output "after second occurrence of label"
$ wait 0::2 ! since we are in a loop this will slow things down
$ goto label ! hit ctrl-y to break out
$
$ continue1: ! the previous "on control_y" remains in force despite having been triggered
$
$ label = "jump"
$ goto 'label ! target can be a variable; talk about handy
$ jump:
$ write sys$output "after first occurrence of jump"
$
$ first_time = "true"
$ continue_label = "continue2"
$ 'continue_label: ! even the label can be a variable (but only backwards); talk about handy
$ if first_time then $ goto skip
$ break = "true"
$ return
$
$ skip:
$ first_time = "false"
$
$ on control_y then $ gosub 'continue_label ! setup a new on control_y to get out the next loop coming up
$
$ break = "false"
$ 'label:
$ write sys$output "after second occurrence of jump"
$ wait 0::2
$ if .not. break then $ goto 'label
$
$ gosub sub1 ! no new scope or parameters
$ label = "sub1"
$ gosub 'label
$
$ call sub4 a1 b2 c3 ! new scope and parameters
$
$ @nl: ! new scope and parameters in another file but same process
$
$ procedure_filename = f$environment( "procedure " ) ! what is our own filename?
$ @'procedure_filename inner
$
$ exit ! exiting outermost scope exits the command procedure altogether, i.e. back to shell
$
$ sub1:
$ return
$
$ sub2:
$ goto break ! structurally disorganized but allowed
$
$ sub3:
$ return
$
$ break:
$ return
$
$ sub4: subroutine
$ exit
$ endsubroutine
- Output:
$ @jump_anywhere after first occurrence of label after second occurrence of label after second occurrence of label Interrupt after first occurrence of jump after second occurrence of jump after second occurrence of jump Interrupt $
Same thing but with verify (tracing) on
- Output:
$ @jump_anywhere $ return ! ignored since we haven't done a gosub yet $ $ if p1 .eqs. "" then $ goto main $ main: $ goto label ! if label hasn't been read yet then DCL will read forward to find label $ label: $ write sys$output "after first occurrence of label" after first occurrence of label $ $ on control_y then $ goto continue1 ! we will use this to get out of the loop that's coming up $ $ label: ! duplicate labels *are* allowed, the most recently read is the one that will be the target $ write sys$output "after second occurrence of label" after second occurrence of label $ wait 0::2 ! since we are in a loop this will slow things down $ goto label ! hit ctrl-y to break out $ label: ! duplicate labels *are* allowed, the most recently read is the one that will be the target $ write sys$output "after second occurrence of label" after second occurrence of label $ wait 0::2 ! since we are in a loop this will slow things down Interrupt $ continue1: ! the previous "on control_y" remains in force despite having been triggered $ $ label = "jump" $ goto jump ! target can be a variable; talk about handy $ jump: $ write sys$output "after first occurrence of jump" after first occurrence of jump $ $ first_time = "true" $ continue_label = "continue2" $ continue2: $ if first_time then $ goto skip $ skip: $ first_time = "false" $ $ on control_y then $ gosub continue2 ! setup a new on control_y to get out the next loop coming up $ $ break = "false" $ jump: ! even the target can be a variable (but only backwards); talk about handy $ write sys$output "after second occurrence of jump" after second occurrence of jump $ wait 0::2 $ if .not. break then $ goto jump $ jump: ! even the target can be a variable (but only backwards); talk about handy $ write sys$output "after second occurrence of jump" after second occurrence of jump $ wait 0::2 Interrupt $ continue2: $ if first_time then $ goto skip $ break = "true" $ return $ if .not. break then $ goto jump $ $ gosub sub1 ! no new scope or parameters $ sub1: $ return $ label = "sub1" $ gosub sub1 $ sub1: $ return $ $ call sub4 a1 b2 c3 ! new scope and parameters $ sub4: subroutine $ exit $ $ @nl: ! new scope and parameters in another file but same process $ $ procedure_filename = f$environment( "procedure " ) ! what is our own filename? $ @DSVE_PAA_ROOT:[NG25957]JUMP_ANYWHERE.COM;1 inner $ return ! ignored since we haven't done a gosub yet $ $ if p1 .eqs. "" then $ goto main $ inner: $ exit $ $ exit ! exiting outermost scope exits the command procedure altogether, i.e. back to shell
Déjà Vu
Déjà Vu supports continuations:
example:
!print "First part"
yield
!print "Second part"
local :continue example
!print "Interrupted"
continue
- Output:
First part Interrupted Second part
The byte-code language supports jumping to arbitrary positions in the same file.
Delphi
Delphi has a goto LABEL keyword. Labels must be declared outside function body scope. 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.
var
x: Integer = 5;
label
positive, negative, both;
begin
if (x > 0) then
goto positive
else
goto negative;
positive:
writeln('pos');
goto both;
negative:
writeln('neg');
both:
readln;
end.
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.
label
inloop, outloop;
begin
x := 2;
if x > 0 then
goto inloop;
for x := -10 to 10 do
begin
inloop:
Writeln(x);
if x = 8 then
goto outloop;
end;
outloop:
readln;
end.
- Output:
2 3 4 5 6 7 8
In Delphi you can't goto a label from within any section of a try .. except or finally block. This won't work.
label
tryAgain, finished;
begin
x := 0;
try
Writeln(x);
inc(x);
if (x < 10) then
goto tryAgain;
finally
goto finished
end;
finished:
readln;
end.
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
- Output:
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
Erlang
Jumps are limited to Exceptions.
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:
PROGRAM GOTO_ERR
LABEL 99,100
PROCEDURE P1
INPUT(I)
IF I=0 THEN GOTO 99 END IF
END PROCEDURE
PROCEDURE P2
99: PRINT("I'm in procdedure P2")
END PROCEDURE
BEGIN
100:
INPUT(J)
IF J=1 THEN GOTO 99 END IF
IF J<>0 THEN GOTO 100 END IF
END PROGRAM
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).
Factor
A lot of things that seem like jumps in Factor are really just tail recursion or quotation manipulation. For instance, breaking out of iteration early with find
consists of satisfying the base case of a recursive combinator. do
simply makes a copy of the body quotation and calls it before proceeding to while
.
For everything else, Factor has continuations. Exception handling, co-operative threads, backtracking, and break (called return
in Factor) are implemented with continuations.
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 current-continuation
.
USING: continuations prettyprint ;
current-continuation short.
- Output:
T{ continuation f ~array~ ~callstack~ ~array~ ~vector~ ~vector~...
Following is a simple example where we reify a continuation before attempting to divide 1 by 0. Note the current execution context (a continuation
object) is placed on the top of the data stack inside the callcc0
quotation which continue
then reifies.
USING: continuations math prettyprint ;
[ 10 2 / . continue 1 0 / . ] callcc0
- Output:
5
We can even reify a continuation while taking an object back with us.
USING: continuations kernel math ;
[ 10 2 / swap continue-with 1 0 / ] callcc1
- Output:
--- Data stack: 5
FBSL
FBSL's BASIC supports labels (jump targets) and the corresponding GoTo and GoSub/Return commands. However, they are considered obsolete and have been superceded in everyday practice by more modern structured programming methods - subprocedures (Subs and Functions), block constructs, loops, and OOP.
FBSL's BASIC labels are denoted with colon prefixes:
:label ' this is a label named "label"
GOTO label ' this is a jump to the label named "label"
and belong to the global namespace. This means they are accessible for the GoTo and GoSub commands from anywhere throughout the script regardless of whether they are defined locally (in a subprocedure) or globally (outside all subprocedures). Consequently, a label's name must be unique throughout the script. Duplicate label names generate a compile-time exception.
FBSL's DynAsm labels may be named or nameless (automatic):
@label ; this is a label named "label"
JMP label ; this is a jump to the label named "label"
@@ ; this is an automatic label
JMP @F ; this is a jump to the nearest @@ label ahead
JMP @B ; this is a jump to the nearest @@ label behind
@@ ; this is another automatic label
and are local to the block they are defined in.
FBSL's DynC labels are denoted with colon postfixes and follow the ANSI C scoping rules:
label: // this is a label named "label"
goto label; // this is a jump to the label named "label"
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
\ as to create a loop. this functions with ficl, pfe,
\ gforth, bigforth, swiftforth, iforth, and vfxforth; it
\ may work with other forths as well.
create goto1 1 cells allot create goto2 1 cells allot
create goto3 1 cells allot create goto4 1 cells allot
create goto5 1 cells allot create goto6 1 cells allot
create goto7 1 cells allot create goto8 1 cells allot
create goto9 1 cells allot create goto10 1 cells allot
: proc1
[ here goto1 ! ] s" item1 " type goto7 @ >r exit
[ here goto2 ! ] s" item2 " type goto8 @ >r exit
[ here goto3 ! ] s" item3 " type goto9 @ >r exit
[ here goto4 ! ] s" item4 " type goto10 @ >r exit
[ here goto5 ! ] s" item5" type cr 2dup = if 2drop exit then 1+ goto6 @ >r ;
: proc2
[ here goto6 ! ] s" line " type dup . s" --> item6 " type goto1 @ >r exit
[ here goto7 ! ] s" item7 " type goto2 @ >r exit
[ here goto8 ! ] s" item8 " type goto3 @ >r exit
[ here goto9 ! ] s" item9 " type goto4 @ >r exit
[ here goto10 ! ] s" item10 " type goto5 @ >r ;
5 1 proc2
bye
Output:
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
\ 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
\ 'goto'. works with ficl, pfe, gforth, bigforth, and vfxforth.
\ swiftforth and iforth crash.
create gotos 10 cells allot \ data structure for storing goto/jump addresses
: mark_goto here swap 1- cells gotos + ! ; immediate \ save addresses for jumping
: goto r> drop 1- cells gotos + @ >r ;
\ designations for commands are immaterial when using goto's,
\ since the commands are not referenced by name, and are instead
\ jumped into by means of the goto marker.
: command1
[ 1 ] mark_goto s" item1 " type 7 goto
[ 2 ] mark_goto s" item2 " type 8 goto
[ 3 ] mark_goto s" item3 " type 9 goto
[ 4 ] mark_goto s" item4 " type 10 goto
[ 5 ] mark_goto s" item5 " type cr 2dup = if 2drop exit then 1+ 6 goto ;
: command2
[ 6 ] mark_goto s" line " type dup . s" --> item6 " type 1 goto
[ 7 ] mark_goto s" item7 " type 2 goto
[ 8 ] mark_goto s" item8 " type 3 goto
[ 9 ] mark_goto s" item9 " type 4 goto
[ 10 ] mark_goto s" item10 " type 5 goto ;
: go 5 1 6 goto ; go
bye
Output:
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
\ works with ficl, pfe, gforth, bigforth, and vfx.
\ swiftforth may crash, iforth does not function.
: create_goto create 4 allot does> r> drop @ >r ;
: mark_goto here ' >body ! ; immediate
create_goto goto1
create_goto goto2
create_goto goto3
create_goto goto4
create_goto goto5
create_goto goto6
create_goto goto7
create_goto goto8
create_goto goto9
create_goto stop_here
:noname
mark_goto goto1 s" iteration " type dup . s" --> " type
s" goto1 " type goto3
mark_goto goto2 s" goto2 " type goto4
mark_goto goto3 s" goto3 " type goto5
mark_goto goto4 s" goto4 " type goto6
mark_goto goto5 s" goto5 " type goto7
mark_goto goto6 s" goto6 " type goto8
mark_goto goto7 s" goto7 " type goto9
mark_goto goto8 s" goto8 " type stop_here
mark_goto goto9 s" goto9 " type goto2 ; drop
:noname mark_goto stop_here
cr 2dup = if 2drop exit then 1+ goto1
\ cr 2dup = if 2drop bye then 1+ goto1 \ for swiftforth
; drop
: go goto1 ;
5 1 go
bye
Output:
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
Minimal Option
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.
: GOTO ['] EXECUTE ;
TEST
: WORLD ." World!" ;
: HELLO ." Hello" ;
GOTO CR GOTO HELLO GOTO SPACE GOTO WORLD
Hello World!
Fortran
Fortran programmers have long been condemned for their usage of GO TO label (a label being an integer only: no text) which can be to any labelled statement in a program unit. That is, within a subroutine (or function) or within the main line. There is no provision for referencing labels outside a program unit, as with jumping from one subroutine into another. Even when F90 introduced the ability to nest routines whereby a routine is defined within another and the inner routine can reference the containing routine's variables, it is not allowed to reference its labels - purely as an intended restriction and despite this being allowed in Algol and PL/I. However, the "alternate return" protocol can be used, whereby a routine is invoked with additional parameters that are not numbers but labels within the calling routine. The called routine can then execute a normal RETURN statement, or say RETURN 2 to return not to the calling location but to the second nominated label in the invocation. By this means, the called routine can jump to some location in the calling routine, in the same way that in READ (IN,*,ERR = 666) X
provides an alternate return for error conditions.
Early Fortran was devised without much worry over "structured" constructions, so it was quite possible to jump into the scope of a DO-loop (perhaps after jumping out) and subsequent results would depend on the method used by the compiler to control the number of iterations that are made. With F77 and the IF ... THEN ... ELSE ... ENDIF constructions, possibly nested, came the chance to jump from one clause to another - say from the ELSE clause to part-way into the THEN clause. As with the DO-loop violation, this behaviour gathered opprobrium and although allowed by the syntax is likely deemed to be an error by later compilers.
As for "Jump Anywhere", some implementations of the computed-GO TO statement really did do a calculate-offset-and-jump so that GO TO (665,666,667), HOP
would produce an array of three addresses indexed by the value of HOP, and if HOP was outside the range of one to three, whatever was found at the indexed location would be taken as the address to jump to... Even worse opportunities might be exercised via the ASSIGN statement, which "assigns" a label to an integer variable as in ASSIGN 666 TO THENCE
- effectively, storing the machine address associated with label 666 to variable THENCE. Such a variable is open to adjustment and might be available via a COMMON storage area to other routines, whose execution of GO TO THENCE
is sure to prove interesting.
FreeBASIC
The default and most modern dialect of FreeBASIC (-lang fb) supports the 'Goto' keyword either on its own or within the following constructs:
- On (Local) Error Goto (requires compilation with -e, -ex or -exx switch)
- On ... Goto
- If ... Goto (deprecated)
'Goto' is always followed by a label which must be a valid identifier and can only jump to locations at the same level (either within the same procedure or within module-level code).
However, a compiler error or warning is issued if 'Goto' skips a variable definition but not the end of the variable's scope. This is intended to prevent potential accesses to unconstructed or uninitialized variables and ensures that automatic destruction never happens to such variables.
'On (Local) Error Goto' can be used for error handling at module level or procedure level. In theory, the 'Local' keyword should restrict error handling to procedure level but currently is ignored by the compiler. It still works with the 'Error' statement, which forces an error to be generated, even if the above compiler switches are not used
'On ... Goto' allows one to define a 'jump table' which jumps to a specific label depending on the value of a variable or expression. A value of 1 will jump to the first label, a value of 2 to the second label and so on.
'If ... Goto' is shorthand for 'If ... Then Goto' in a single line 'If' statement. It's an old construct which is now deprecated but still works.
In the other dialects of FreeBASIC, 'Goto' behaves in a similar fashion except that:
- In the -lang qb dialect, labels can still be line numbers for compatibility with old QuickBasic code.
- 'Goto' is allowed to skip uninitialized variables in the -lang qb and -lang fblite dialects because these dialects do not support nested scopes and all local variable declarations are moved to the top of their procedures.
- The -lang qb dialect also supports the 'Gosub' and 'On ... Gosub' constructs which (on execution of the 'Return' statement) return to the location from which they were called. In the -lang fblite dialect these constructs are disabled by default - you have to use the 'Option Gosub' statement to turn them on or 'Option NoGosub' statement to turn them off again.
- The -lang qb and -lang fblite dialects also support the 'Resume' and 'Resume Next' statements in conjunction with the 'On (Local) Error Goto' statement (requires compilation with -ex or -exx switch). These statements resume execution at the current or next line, respectively, following the execution of the error handling routine.
None of the FreeBASIC dialects support jumping out of multiple procedures or continuations. However, you can leave procedures prematurely (and rejoin the calling procedure or module-level code) using the 'Exit ... ' or 'Return ...' statements.
The following program demonstrate the use of the various 'Goto' constructs in the -lang fb dialect only:
' FB 1.05.0 Win64
' compiled with -lang fb (the default) and -e switches
Sub MySub()
Goto localLabel
Dim a As Integer = 10 '' compiler warning that this variable definition is being skipped
localLabel:
Print "localLabel reached"
Print "a = "; a '' prints garbage as 'a' is uninitialized
End Sub
Sub MySub2()
On Error Goto handler
Open "zzz.zz" For Input As #1 '' this file doesn't exist!
On Error Goto 0 '' turns off error handling
End
handler:
Dim e As Integer = Err '' cache error number before printing message
Print "Error number"; e; " occurred - file not found"
End Sub
Sub MySub3()
Dim b As Integer = 2
On b Goto label1, label2 '' jumps to label2
label1:
Print "Label1 reached"
Return '' premature return from Sub
label2:
Print "Label2 reached"
End Sub
Sub MySub4()
Dim c As Integer = 3
If c = 3 Goto localLabel2 '' better to use If ... Then Goto ... in new code
Print "This won't be seen"
localLabel2:
Print "localLabel2 reached"
End Sub
MySub
MySub2
MySub3
MySub4
Print
Print "Pres any key to quit"
Print
- Output:
localLabel reached a = 5 Error number 2 occurred - file not found Label2 reached localLabel2 reached
FutureBasic
FB supports both goto and gosub.
The goto statement causes program execution to continue at the statement at the indicated line number or statement label. The target statement must be within the same "scope" as the goto statement (i.e., they must both be within the "main" part of the program, or they must both be within the same local function). Also, you should not use goto to jump into the middle of any "block" statement structures (such as for...next, select...end select, long if...end if, etc.).
The gosub statement should include a return statement; return causes execution to continue at the statement following the gosub statement.
All that said, don't use spaghetti code -- use functions. You can still by spark plugs for a 1985 Yugo, but why?
window 1
print "First line."
gosub "sub1"
print "Fifth line."
goto "Almost over"
"sub1"
print "Second line."
gosub "sub2"
print "Fourth line."
return
"Almost over"
print "We're just about done..."
goto "Outa here"
"sub2"
print "Third line."
return
"Outa here"
print "... with goto and gosub, thankfully."
HandleEvents
Output:
First line. Second line. Third line. Fourth line. Fifth line. We're just about done... ... with goto and gosub, thankfully.
Go
Go has labelled 'break' and 'continue' statements which enable one to easily break out of a nested loop or continue with a containing loop.
Go also has a 'goto' statement which allows one to jump to a label in the same function. However, 'goto' is not allowed to jump over the creation of new variables or to jump to a label inside a block from outside that block.
For example:
package main
import "fmt"
func main() {
outer:
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
if i + j == 4 { continue outer }
if i + j == 5 { break outer }
fmt.Println(i + j)
}
}
k := 3
if k == 3 { goto later }
fmt.Println(k) // never executed
later:
k++
fmt.Println(k)
}
- Output:
0 1 2 3 1 2 3 2 3 3 4
package main import "fmt" func main() { // defer run last defer fmt.Println("World") fmt.Println("Hello") // goto i := 0 Here: if i < 5 { fmt.Println(i) i++ goto Here } else { fmt.Println("i is less than 5") } // break & continue number := 0 for { number++ if number > 3 { break } if number == 2 { continue } fmt.Printf("%v\n", number) } } // init func init() { fmt.Println("run first") }
Harbour
Harbour has no labels and goto statements. The exit statements allows leave the current loop and doesn't contain any label where to go.
Haskell
Haskell being pure functional language doesn't need labels or goto's. However it is flexible and powerful enough to implement imperative constructions using monads. Hackage has a library GoToT-transformers. This module provides a Goto
monad and corresponding monad transformer that allow the user to transfer the flow of execution from an arbitrary point of a monadic computation to another monadic computation. It works with any monad, not only with IO
.
We show possible implementation of goto
, given here, with some simplifications.
First some boilerplate, where we define labels and goto "operator".
import Control.Monad.Cont
data LabelT r m = LabelT (ContT r m ())
label :: ContT r m (LabelT r m)
label = callCC subprog
where subprog lbl = let l = LabelT (lbl l) in return l
goto :: LabelT r m -> ContT r m b
goto (LabelT l) = const undefined <$> l
runProgram :: Monad m => ContT r m r -> m r
runProgram program = runContT program return
Here is example of using labels in IO:
main = runProgram $
do
start <- label
lift $ putStrLn "Enter your name, please"
name <- lift $ getLine
if name == ""
then do lift $ putStrLn "Name can't be empty!"
goto start
else lift $ putStrLn ("Hello, " ++ name)
- Output:
λ> main Enter your name, please Name can't be empty! Enter your name, please John Hello, John
We can build tiny EDSL to get rid of explicit lifting and to add refferences:
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
and implement famous Euclid's algorithm as an imperative program:
gcdProg = runProgram $ callCC $ \exit -> -- <--------+
do -- |
start <- label -- <-----+ |
output "Enter two integers, or zero to exit" -- | |
nr <- readInt -- | |
n <- get nr -- | |
when (n == 0) $ -- | |
do output "Exiting" -- | |
exit () -- ---------+
mr <- readInt -- |
loop <- label -- <--+ |
n <- get nr -- | |
m <- get mr -- | |
when (n == m) $ -- | |
do output ("GCD: " ++ show n) -- | |
goto start -- ------+
when (n > m) $ set nr (n - m) -- |
when (m > n) $ set mr (m - n) -- |
goto loop -- ---+
- Output:
λ> gcdProg Enter two integer numbers, or zero to exit 12 15 GCD: 3 Enter two integer numbers, or zero to exit 0 Exiting
In native Haskell such flow jumps are done by function calls:
gcdFProg = start
where
start = do
putStrLn "Enter two integers, or zero to exit"
n <- readLn
if n == 0
then
putStrLn "Exiting"
else do
m <- readLn
putStrLn $ "GCD: " ++ show (loop n m)
start
loop n m
| n == m = n
| n < m = loop n (m-n)
| n > m = loop (n-m) m
Or without explicit recursion and branching:
import Control.Applicative
import Control.Monad.Trans.Maybe
gcdFProg2 = forever mainLoop <|> putStrLn "Exiting"
where
mainLoop = putStrLn "Enter two integers, or zero to exit" >>
runMaybeT process >>=
maybe empty (\r -> putStrLn ("GCD: " ++ show r))
process = gcd <$> (lift readLn >>= exitOn 0) <*> lift readLn
exitOn n x = if x == n then empty else pure x
i
//'i' does not have goto statements, instead control flow is the only legal way to navigate the program.
concept there() {
print("Hello there")
return //The return statement goes back to where the function was called.
print("Not here")
}
software {
loop {
break //This breaks the loop, the code after the loop block will be executed next.
print("This will never print")
}
loop {
loop {
loop {
break //This breaks out of 1 loop.
}
print("This will print")
break 2 //This breaks out of 2 loops.
}
print("This will not print")
}
//Move to the code contained in the 'there' function.
there()
}
J
J allows control to be passed to any named verb at any time. When the verb completes, control returns to the caller, unless an unhandled exception was raised (or unless a handled exception was raised, where the handler is outside the caller).
For example:
F=: verb define
smoutput 'Now we are in F'
G''
smoutput 'Now we are back in F'
)
G=: verb define
smoutput 'Now we are in G'
throw.
)
F''
Now we are in F
Now we are in G
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):
H=: verb define
smoutput 'a'
label_b.
smoutput 'c'
goto_f.
label_d.
smoutput 'e' return.
label_f.
smoutput 'g'
goto_d.
smoutput 'h'
)
H''
a
c
g
e
Java
The closest thing that Java has to a "goto" is labelled loops:
loop1: while (x != 0) {
loop2: for (int i = 0; i < 10; i++) {
loop3: do {
//some calculations...
if (/*some condition*/) {
//this continue will skip the rest of the while loop code and start it over at the next iteration
continue loop1;
}
//more calculations skipped by the continue if it is executed
if (/*another condition*/) {
//this break will end the for loop and jump to its closing brace
break loop2;
}
} while (y < 10);
//loop2 calculations skipped if the break is executed
}
//loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed
}
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 try/catch/finally to jump to the right places for printing:
public class FizzBuzzThrower {
public static void main( String [] args ) {
for ( int i = 1; i <= 30; i++ ) {
try {
String message = "";
if ( i % 3 == 0 ) message = "Fizz";
if ( i % 5 == 0 ) message += "Buzz";
if ( ! "".equals( message ) ) throw new RuntimeException( message );
System.out.print( i );
} catch ( final RuntimeException x ) {
System.out.print( x.getMessage() );
} finally {
System.out.println();
}
}
}
}
jq
jq supports named labels ("label $NAME") and break statements ("break $NAME"). Usage follows the pattern:
label $out | ... break $out ...
When, during program execution, a "break" statement is encountered, the program continues as though the nearest `label $label_name` statement on the left produced `empty`.
The label specified by the "break" statement has to be visible (in the sense of being within scope) at the break statement.
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:
label $out | 1e7 | while(true; .+1) | if (1/.) | . == sin then (., break $out) else empty end
Here, the "while" filter is an unbounded generator. The answer is 46530688.
The main reason why jq has a "break" statement is so that various control structures, such as the short-circuiting control structures "any" and "all", can be implemented in jq itself.
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:
1e7 | until(1/. | . == sin; .+1)
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.
function example()
println("Hello ")
@goto world
println("Never printed")
@label world
println("world")
end
Kotlin
Kotlin does not have a 'goto' statement but does have labelled 'break' and 'continue' statements which enable one to easily break out of a nested loop or continue with a containing loop.
Kotlin also has a labelled 'return' statement to return from a nested function or lambda expression.
For example:
// version 1.0.6
fun main(args: Array<String>) {
intArrayOf(4, 5, 6).forEach lambda@ {
if (it == 5) return@lambda
println(it)
}
println()
loop@ for (i in 0 .. 3) {
for (j in 0 .. 3) {
if (i + j == 4) continue@loop
if (i + j == 5) break@loop
println(i + j)
}
}
}
- Output:
4 6 0 1 2 3 1 2 3 2 3 3
Lingo
- Lingo does not support jumping to markers ("goto").
- Lingo supports "unwinding the call stack" via the abort command that exits the current call stack:
on foo
abort()
end
on bar ()
foo()
put "This will never be printed"
end
- Rarely used, but Lingo supports saving a continuation via the play ... play done construct:
on testPlayDone ()
-- Start some asynchronous process (like e.g. a HTTP request).
-- The result might be saved in some global variable, e.g. in _global.result
startAsyncProcess()
-- pauses execution of current function
play(_movie.frame)
-- 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
Logtalk
Jumps are limited to Exceptions.
Lua
Lua 5.2 introduced a goto
statement along with labels. It was somewhat controversially implemented instead of a continue
keyword, but it is more flexible and supports other types of jumps as well. goto
only supports statically-defined labels.
-- Forward jump
goto skip_print
print "won't print"
::skip_print::
-- Backward jump
::loop::
print "infinite loop"
goto loop
-- Labels follow the same scoping rules as local variables, but with no equivalent of upvalues
goto next
do
::next:: -- not visible to above goto
print "won't print"
end
::next:: -- goto actually jumps here
-- goto cannot jump into or out of a function
::outside::
function nope () goto outside end -- error: no visible label 'outside' for <goto> at line 2
goto inside
function nope () ::inside:: end -- error: no visible label 'inside' for <goto> at line 1
-- Convenient for breaking out of nested loops
for i = 1, 10 do
for j = 1, 10 do
for k = 1, 10 do
if i^2 + j^2 == k^2 then
print(("found: i=%d j=%d k=%d"):format(i, j, k))
goto exit
end
end
end
end
print "not found"
::exit::
M2000 Interpreter
We can use basic like numbers, and Goto, On Goto, Gosub, On Gosub, and an Exit For to specific label.
We can place statements right in a label if is numeric. If label is not numeric we can place rem only using ' or \
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
Module Checkit {
Module Alfa {
10 Rem this code is like basic
20 Let K%=1
30 Let A=2
40 Print "Begin"
50 On K% Gosub 110
60 If A=2 then 520
70 For I=1 to 10
80 if i>5 then exit for 120
90 Gosub 110
100 Next i
110 On A Goto 150, 500
120 Print "This is the End ?"
130 Return
150 Print "from loop pass here", i
160 Return
200 Print "ok"
210 Return
500 Print "Routine 500"
510 Goto 200
520 Let A=1
530 Gosub 70
540 Print "Yes"
}
Alfa
\\ this can be done. Code executed like it is from this module
\\ because 200 is a label inside code of Module Checkit
\\ and search is not so smart. After first search. position saved in a hash table
Gosub 200 ' print "ok"
Gosub 200 ' print "ok"
}
Checkit
Simulate Run Basic Entry
Module LikeRunBasic {
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
}
end
label6:
print i
if i = 6 then goto finish
print "Why am I here"
finish:
print "done"
}
LikeRunBasic
Simulate Go Entry
Module LikeGo {
\\ simulate Go for
\\ need to make var Empty, swapping uninitialized array item
Module EmptyVar (&x) {
Dim A(1)
Swap A(0), x
}
Function GoFor(&i, first, comp$, step$) {
\\ checking for empty we now if i get first value
if type$(i)="Empty" then {
i=first
} else {
i+=Eval(step$)
}
if Eval("i"+comp$) Else Exit
=true
}
def i, j
EmptyVar &i
outer:
{
if GoFor(&i, 0, "<4", "+1") else exit
EmptyVar &j
{
if GoFor(&j, 0, "<4", "+1") else exit
if i+j== 4 then goto outer
if i+j == 5 then goto break_outer
print i+j
loop
}
loop
}
break_outer:
k = 3
if k == 3 Then Goto later
Print k \\ never executed
later:
k++
Print k
}
LikeGo
\\ or we can use For {} block and put label outer to right place
Module LikeGo {
For i=0 to 3 {
For j=0 to 3 {
if i+j== 4 then goto outer
if i+j == 5 then goto break_outer
print i+j
}
outer:
}
break_outer:
k = 3
if k == 3 Then Goto later
Print k \\ never executed
later:
k++
Print k
}
LikeGo
Module LikeGo_No_Labels {
For i=0 to 3 {
For j=0 to 3 {
if i+j== 4 then exit ' exit breaks only one block
if i+j == 5 then break ' break breaks all blocks, but not the Module's block.
print i+j
}
}
k = 3
if k == 3 Else {
Print k \\ never executed
}
k++
Print k
}
LikeGo_No_Labels
Mathematica /Wolfram Language
Mathematica and the Wolfram Language supports non-local jumps to a previous Catch[] (via Throw[]).
There is Goto[Label] function in Mathematica. This allows "jumps" to arbitrary locations within (the same or other) functions.
MBS
goto mylabel;
МК-61/52
БП XX
XX is any address.
MIPS Assembly
j
, jr
, jal
, and jalr
are able to take you to anywhere in the CPU's address space.
-
j 0xNNNNNNNN
sets the program counter equal to0xNNNNNNNN
. -
jr $NN
sets the program counter equal to the value in register$NN
. -
jal 0xNNNNNNNN
sets the program counter equal to0xNNNNNNNN
, and moves the old program counter plus 8 into register$ra
. -
jalr $NN,0xNNNNNNNN
sets the program counter equal to0xNNNNNNNN
and moves the old program counter plus 8 into register$NN
.
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.
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.
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 j
. The actual offset is calculated during the assembly process, which means you don't have to measure it yourself by counting bytes.
MUMPS
You can go to any point in any routine in the same namespace. In some implementations, you can even go between namespaces. It's not recommended though.
Some interpreters will allow you jump between blocks of the same depth. Others will let you leave, but not enter, a block.
;Go to a label within the program file
Goto Label
;Go to a line below a label
Goto Label+lines
;Go to a different file
Goto ^Routine
;Go to a label within a different file
Goto Label^Routine
;and with offset
Goto Label+2^Routine
;
;The next two goto commands will both return error M45 in ANSI MUMPS.
NoNo
For
. Goto Out
Out Quit
Goto NoNo+2
Neko
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.
$print("start\n")
$goto(skip)
$print("Jumped over")
skip:
$print("end\n")
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.
Nim
Nim has exceptions and labelled breaks:
block outer:
for i in 0..1000:
for j in 0..1000:
if i + j == 3:
break outer
Oforth
Oforth has no goto and no labels.
Apart from exceptions handling (see exceptions tasks), Oforth has continue (to go to next loop) and break (to leave a loop).
Ol
No jumps in Ol because Ol is purely functional language.
Some portion of code can be restarted (as recursion) and skipped (as continuation).
; recursion:
(let loop ((n 10))
(unless (= n 0)
(loop (- n 1))))
; continuation
(call/cc (lambda (break)
(let loop ((n 10))
(if (= n 0)
(break 0))
(loop (- n 1)))))
(print "ok.")
PARI/GP
GP lacks gotos and continuations, but can break out of arbitrarily many nested loops with break(n)
which can be used to simulate goto within a given function. It can also use local
values or error
to break out of several layers of function calls, if needed.
PARI inherits C's ability to goto
or longjmp
; the latter is used extensively in the library.
PascalABC.NET
label finish;
begin
var a := MatrRandomInteger(3,4);
var found := False;
for var i:=0 to a.RowCount-1 do
for var j:=0 to a.ColCount-1 do
if a[i,j] = 10 then
begin
found := True;
goto finish;
end;
finish:
Print(found);
end.
Perl
Perl's goto LABEL
and goto EXPR
are a little too powerful to be safe. Use only under extreme duress (actually, not even then). goto &SUB
is esoteric but much more innocuous and can occasionally be handy.
sub outer {
print "In outer, calling inner:\n";
inner();
OUTER:
print "at label OUTER\n";
}
sub inner {
print "In inner\n";
goto SKIP; # goto same block level
print "This should be skipped\n";
SKIP:
print "at label SKIP\n";
goto OUTER; # goto whatever OUTER label there is on frame stack.
# if there isn't any, exception will be raised
print "Inner should never reach here\n";
}
sub disguise {
goto &outer; # a different type of goto, it replaces the stack frame
# with the outer() function's and pretend we called
# that function to begin with
print "Can't reach this statement\n";
}
print "Calling outer:\n";
outer();
print "\nCalling disguise:\n";
disguise();
print "\nCalling inner:\n";
inner(); # will die
Phix
In Phix, when absolutely necessary, gotos and labels can be implemented using inline assembly. 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.
#ilASM{ jmp :%somelabel }
...
#ilASM{ :%somelabel }
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
#ilASM{ jmp :local
...
::local }
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
#ilASM{ jmp @f
...
@@:
...
jle @b }
There are also optional (global) labels:
#ilASM{ call :!optlbl
[32]
pop eax
[64]
pop rax
[]
...
:!optlbl
[32]
push dword[esp]
[64]
push qword[rsp]
[]
ret }
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.
Optional labels are most heavily used as part of the run-time diagnostics, for example pDiagN.e contains lines such as cmp edx,:!opXore92a
which checks to see whether an
invalid memory access wants mapping to a "variable has not been assigned a value" error (and retrieve the correct return address for any error that occurs at that specific location);
if xor
is not used/included, the instruction quietly resolves to cmp edx,0.
Lastly (for completeness) there are init labels, defined using
#ilASM{ :>init }
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.
Obviously there are also several hll keywords such as exit
and return
which can often be used to achieve the same effect in a much more structured fashion.
PicoLisp
PicoLisp supports non-local jumps to a previously setup environment (see exceptions) via 'catch' and 'throw', or to some location in another coroutine with 'yield' (see generator).
'quit' is similar to 'throw', but doesn't require a corresponding 'catch', as it directly jumps to the error handler (where the program may catch that error again).
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":
(de foo (N)
(prinl "This is 'foo'")
(printsp N)
(or (=0 (dec 'N)) (run (cddr foo))) )
Test:
: (foo 7) This is 'foo' 7 6 5 4 3 2 1 -> 0
PL/I
The goto
statement causes control to be transferred to a labeled statement in the current or any outer procedure.
A goto
statement cannot transfer control:
- Into an inactive
begin
block. - From outside into a
do
group.
In structured programming, the only place where a goto
can be is inside on
units to handle exceptions without recursion.
on conversion goto restart;
PL/SQL
PL/SQL supports both GOTOs and structured exception handling:
DECLARE
i number := 5;
divide_by_zero EXCEPTION;
PRAGMA exception_init(divide_by_zero, -20000);
BEGIN
DBMS_OUTPUT.put_line( 'startLoop' );
<<startLoop>>
BEGIN
if i = 0 then
raise divide_by_zero;
end if;
DBMS_OUTPUT.put_line( 100/i );
i := i - 1;
GOTO startLoop;
EXCEPTION
WHEN divide_by_zero THEN
DBMS_OUTPUT.put_line( 'Oops!' );
GOTO finally;
END;
<<endLoop>>
DBMS_OUTPUT.put_line( 'endLoop' );
<<finally>>
DBMS_OUTPUT.put_line( 'Finally' );
END;
/
- Output:
startLoop 20 25 33.33333333333333333333333333333333333333 50 100 Oops! Finally
PowerShell
A Break statement can include a label. If you use the Break keyword with a label, Windows PowerShell exits the labeled loop instead of exiting the current loop. The syntax for a label is as follows (this example shows a label in a While loop):
:myLabel while (<condition>) { <statement list>}
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 keyword, such as While.
In Windows PowerShell, only loop keywords, such as Foreach, For, and While
can have a label.
Break moves execution out of the labeled loop. In embedded loops, this has
a different result than the Break keyword has when it is used by itself.
This schematic example has a While statement with a For statement:
:myLabel while (<condition 1>)
{
for ($item in $items)
{
if (<condition 2>) { break myLabel }
$item = $x # A statement inside the For-loop
}
}
$a = $c # A statement after the labeled While-loop
If condition 2 evaluates to True, the execution of the script skips down to the statement after the labeled loop. In the example, execution starts again with the statement "$a = $c".
You can nest many labeled loops, as shown in the following schematic example.
:red while (<condition1>)
{
:yellow while (<condition2>)
{
while (<condition3>)
{
if ($a) {break}
if ($b) {break red}
if ($c) {break yellow}
}
# After innermost loop
}
# After "yellow" loop
}
# After "red" loop
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 True, execution of the script control resumes after the loop that is labeled "yellow".
If the $a variable evaluates to True, execution resumes after the innermost loop. No label is needed.
Windows PowerShell does not limit how far labels can resume execution. The label can even pass control across script and function call boundaries.
PureBasic
OnErrorGoto(?ErrorHandler)
OpenConsole()
Gosub label4
Goto label3
label1:
Print("eins ")
Return
label2:
Print("zwei ")
Return
label3:
Print("drei ")
label4:
While i<3
i+1
Gosub label1
Gosub label2
Wend
Print("- ")
i+1
If i<=4 : Return : EndIf
x.i=Val(Input()) : y=1/x
Input()
End
ErrorHandler:
PrintN(ErrorMessage()) : Goto label4
- Output:
eins zwei eins zwei eins zwei - drei -
Python
Python has both exceptions and generators but no unstructured goto ability.
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 here. It is well documented and comes with many examples. My favorite:
# Example 2: Restarting a loop:
from goto import goto, label
label .start
for i in range(1, 4):
print i
if i == 2:
try:
output = message
except NameError:
print "Oops - forgot to define 'message'! Start again."
message = "Hello world"
goto .start
print output, "\n"
It goes the extra mile and adds a comefrom
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.
QBasic
QBasic supports both goto
and gosub
.
PRINT "First line."
GOSUB sub1
PRINT "Fifth line."
GOTO Ending
sub1:
PRINT "Second line."
GOSUB sub2
PRINT "Fourth line."
RETURN
Ending:
PRINT "We're just about done..."
GOTO Finished
sub2:
PRINT "Third line."
RETURN
Finished:
PRINT "... with goto and gosub, thankfully."
END
- Output:
Igual que la entrada de FutureBasic.
QB64
' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic
' here a GOTO demo of loops FOR-NEXT and WHILE-WEND
Dim S As String, Q As Integer
Randomize Timer
0:
Locate 1, 1: Print "jump demostration"
Print "Press J to jump to FOR NEXT emulator or"
Print "L to jump to WHILE WEND emulator or"
Print "Q for quitting"
Print
S = UCase$(Input$(1))
Cls , Rnd * 7 + 1: Locate 7
Q = 0
If S = "Q" Then End
If S = "J" Then GoTo 1
If S = "L" Then GoTo 2
GoTo 0
1:
If Q = 0 Then Print "FOR NEXT Loop emulation"
Print " Q = "; Q
Q = Q + 1
If Q < 10 Then
GoTo 1
Else
Print "For Next emulation terminated":
GoTo 0
End If
2:
If Q = 0 Then Print " WHILE WEND emulator"
Print " Q = 9 is ";
If Q = 9 Then
Print "True"
Print "WHILE WEND emulator terminated"
GoTo 0
Else
Print "False"
End If
Q = Q + 1
GoTo 2
Quackery
One way of thinking about Quackery is as an assembly language for a virtual Quack Processor. A Quack Processor is a Stack Processor which does not interact directly with computer memory, but sends requests to a co-processor that specialises in dynamic memory allocation and garbage collection of dynamic arrays. (In practice this is a pretty way of saying "lets Python (the language Quackery is implemented in) do the heavy lifting.").
In Quackery these dynamic arrays, which can be summoned at will, are called nests, and nests contain zero or more numbers (bigints), operators (op-codes), and nests. All nests are editable and executable, and execution consists of traversing a nest from left to right, putting numbers on the stack, performing operators and recursively traversing nests within nests.
This traversal cannot be modified directly, none of the operators can modify the pointer to the current nest or the offset into the nest. (One outcome of having a dynamic memory models is that instead of just using a memory address, you also need a pointer to indicate which nest you are referring to.)
Control flow is achieved by tampering with the call stack that the processor uses to store a nest pointer and offset pair each time it encounters a nest. These are the meta-flow operators, which can be thought of as "granting powers" to their calling nest.
So, for example, the word if
conditionally skips over the next item in a nest, iff
conditionally skips over the next two items in a nest, and else
always skips over the next item in a nest, so you would use if (item)
to create an if statement without an else clause, and iff (item) else (item)
for one with an else clause.
They are defined, respectively as [ ]if[ ] is if
, [ ]iff[ ] is iff
, and [ ]else[ ] is else
, where the meta-flow words ]if[
, ]iff[
, and ]else[
work by adding (or not adding) 1 or 2 to the offset on the pointer-offset pair on the top of the call stack.
These, and the rest of the meta-flow operators, are the tools with which the Quackery programmer can build new and novel control flow operators. The meta-flow word-set (used to build Quackery's "mix and match" control-flow word-set) lends itself to single-entry point into a nest, but can be subverted to do all sorts of shenanigans. It includes the word ]bail-by[
, which removes a specified number of pointer+offset pairs from the call stack, intended for use by Quackery's exception handling word bail
, (see Exceptions#Quackery) but available for mischief. Other control flow high jinks may require some deviousness.
The complete meta-flow word set is ]done[ ]again[ ]if[ ]iff[ ]else[ ]'[ ]this[ ]do[ ]bailby[
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 jump-into
, which will start evaluation of a nest a specified distance in. done
causes evaluation of the nest to terminate early (via ]done[
, which removes a pointer-offset pair from the call stack) and again
causes a jump to the start of the nest. (]again[
sets the number in the pair on the top of the call stack to 0.) So 5 jump-into
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, ]'[
advances the offset on top of the return stack, like ]else[
, but also puts a copy of the item skipped over on the stack. (i.e. the nest following jump-into
in the example) It puts this, with an offset of 0, onto the call stack (with ]do[
. Then it uses ' ]else[ swap of
to build a nest of the specified number of instances of ]else[
, and puts that on the call stack, so that it will be evaluated after exiting jump-to
, and increment the offset of the top of the call stack (i.e. the nest following jump-to
) that number of times.
[ ]'[ ]do[ ' ]else[ swap of ]do[ ] is jump-into ( n --> )
5 jump-into
[ 0 echo 1 echo done
( 0 1 2 3 4 offsets of each item )
( 5 6 7 8 9 from start of nest )
2 echo 3 echo again ]
- Output:
2301
Racket
Racket, being a descendant of Scheme, supports full continuations.
As a little example:
#lang racket
(define (never-divides-by-zero return)
(displayln "I'm here")
(return "Leaving")
(displayln "Never going to reach this")
(/ 1 0))
(call/cc never-divides-by-zero)
; outputs:
; I'm here
; "Leaving" (because that's what the function returns)
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.
A much more complicated example done here Where we generate elements of a list one at a time:
#lang racket
;; [LISTOF X] -> ( -> X u 'you-fell-off-the-end-off-the-list)
(define (generate-one-element-at-a-time a-list)
;; (-> X u 'you-fell-off-the-end-off-the-list)
;; this is the actual generator, producing one item from a-list at a time
(define (generator)
(call/cc control-state))
;; [CONTINUATION X] -> EMPTY
;; hand the next item from a-list to "return" (or an end-of-list marker)'
(define (control-state return)
(for-each
(lambda (an-element-from-a-list)
(set! return ;; fixed
(call/cc
(lambda (resume-here)
(set! control-state resume-here)
(return an-element-from-a-list)))))
a-list)
(return 'you-fell-off-the-end-off-the-list))
;; time to return the generator
generator)
Relation
Relation has no jumps.
Retro
Retro allows the user to jump to any address.
:foo #19 &n:inc \ju...... #21 ;
When executed, the stack will contain 20; control does not return to the foo function.
Raku
(formerly Perl 6)
Label-based jumps
outer-loop: loop {
inner-loop: loop {
# NYI # goto inner-loop if rand > 0.5; # Hard goto
next inner-loop if rand > 0.5; # Next loop iteration
redo inner-loop if rand > 0.5; # Re-execute block
last outer-loop if rand > 0.5; # Exit the loop
ENTER { say "Entered inner loop block" }
LEAVE { say "Leaving inner loop block" }
}
ENTER { say "Entered outer loop block" }
LEAVE { say "Leaving outer loop block" }
LAST { say "Ending outer loop" }
}
Produces random output, but here's a representative run:
Entered outer loop block Entered inner loop block Leaving inner loop block Entered inner loop block Leaving inner loop block Entered inner loop block Leaving inner loop block Leaving outer loop block Ending outer loop
Continuation-based execution
Continuations in Raku are currently limited to use in generators via the gather/take model:
my @list = lazy gather for ^100 -> $i {
if $i.is-prime {
say "Taking prime $i";
take $i;
}
}
say @list[5];
This outputs:
Taking prime 2 Taking prime 3 Taking prime 5 Taking prime 7 Taking prime 11 Taking prime 13 13
Notice that no further execution of the loop occurs. If we then asked for the element at index 20, we would expect to see 15 more lines of "Taking prime..." followed by the result: 73.
Failures and exceptions
Exceptions are fairly typical in Raku:
die "This is a generic, untyped exception";
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.
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
Produces:
Called foo foo not true foo not defined oops in sub foo at fail.p6 line 1 in block <unit> at fail.p6 line 2 Actually thrown at: in any at gen/moar/m-Metamodel.nqp line 3090 in block <unit> at fail.p6 line 6
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).
sub foo($i) {
if $i == 0 {
die "Are you sure you want /0?";
}
say "Dividing by $i";
1/$i.Num + 0; # Fighting hard to make this fail
}
for ^10 -> $n {
say "1/$n = " ~ foo($n);
}
CATCH {
when ~$_ ~~ m:s/Are you sure/ { .resume; #`(yes, I'm sure) }
}
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:
Dividing by 0 Attempt to divide 1 by zero using / in sub foo at fail.p6 line 6 in block <unit> at fail.p6 line 10 Actually thrown at: in sub foo at fail.p6 line 6 in block <unit> at fail.p6 line 10
REXX
REXX signal
Note: some REXXes don't allow jumping into a DO loop, although the language specificiations appear to allow it,
as long as the END or the DO loop isn't executed.
The following used PC/REXX to illustrate this example.
/*REXX pgm demonstrates various jumps (GOTOs). In REXX, it's a SIGNAL. */
say 'starting...'
signal aJump
say 'this statement is never executed.'
aJump: say 'and here we are at aJump.'
do j=1 to 10
say 'j=' j
if j==7 then signal bJump
end /*j*/
bJump: say 'and here we are at bJump.'
signal cJump
say 'this statement is never executed.'
do k=1 to 10
say 'k=' k
cJump: say 'and here we are at cJump.'
exit
end /*k*/
- Output:
starting... and here we are at aJump. j= 1 j= 2 j= 3 j= 4 j= 5 j= 6 j= 7 and here we are at bJump. and here we are at cJump.
compared to PL/I goto
After a rather longwinded discussion on the subject I offer here my view: Whereas PL/I disallows the use of GOTO to jump to anywhere
Compiler Messages Message Line.File Message Description IBM1847I S 212.0 GOTO target is inside a (different) DO loop.
Rexx is very liberal as to the use of Signal.
As mentioned above some implementations may have restrictions on that.
This Signal jumps into a Do loop inside a Procedure:
i=13
signal label
say 'This is never executed'
sub: Procedure Expose i
Do i=1 To 10;
label:
Say 'label reached, i='i
Signal real_start
End
Return
real_start:
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:
/* REXX ***************************************************************
* 12.12.2012 Walter Pachl
**********************************************************************/
Signal On Syntax
Parse Upper Arg part
If part<>'' Then
Interpret 'Signal' part
Say 'Executing default part'
Signal eoj
a:Say 'executing part A'
Signal eoj
b:Say 'executing part B'
Signal eoj
Syntax:
Say 'argument must be a or b or omitted'
Exit
eoj: say 'here we could print statistics'
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.
Ring
Ring has no labels and goto statements. The exit statements allows leave the current loop and doesn't contain any label where to go.
Robotic
There are multiple ways to use labels and goto statements.
Simple
A simple example of labels and goto:
. "The label 'touch' is used to let the player touch the robot"
. "to execute the following"
end
: "touch"
goto "label_b"
: "label_a"
* "Label A was reached"
end
: "label_b"
* "Label B was reached"
end
It prints "Label B was reached", skipping "label_a" entirely.
Conditional
This will jump to a given label, depending on the condition of "local1":
set "local1" to 2
end
: "touch"
if "local1" = 1 then "label_a"
if "local1" = 2 then "label_b"
end
: "label_a"
* "Label A was reached"
end
: "label_b"
* "Label B was reached"
end
Since "local1" equals 2, it prints "Label B was reached".
Label Zapping
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:
end
: "touch"
goto "label_a"
: "label_a"
* "Label A was reached"
zap "label_a" 1
end
: "label_a"
* "Alternate Label A was reached"
restore "label_a" 1
end
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.
Subroutines
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 (#):
. "The 'wait' statements are used to demonstrate what is happening"
set "local1" to 1
end
: "touch"
goto "#label_a"
wait for 50
* "Done with Label A"
wait for 50
goto "#label_b"
wait for 50
* "Skipped finishing Label B and C"
end
: "#label_a"
* "Label A was reached"
goto "#return"
: "#label_b"
* "Label B was reached"
wait for 50
goto "#label_d"
: "#label_c"
* "Label C was reached"
goto "#return"
: "#label_d"
* "Label D was reached"
goto "#top"
The following is printed out in order:
Label A was reached
Done with Label A
Label B was reached
Label D was reached
Skipped finishing Label B and C
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").
Ruby
Ruby programs almost never use continuations. MRI copies the call stack when it saves or calls a continuation, so continuations are slow.
The next example abuses a continuation to solve FizzBuzz#Ruby. It is slower and more confusing than an ordinary loop.
require 'continuation' unless defined? Continuation
if a = callcc { |c| [c, 1] }
c, i = a
c[nil] if i > 100
case 0
when i % 3
print "Fizz"
case 0
when i % 5
print "Buzz"
end
when i % 5
print "Buzz"
else
print i
end
puts
c[c, i + 1]
end
This code uses the Continuation object c
to jump to the top of the loop. For the first iteration, callcc
creates c
and returns [c, 1]
. For later iterations, callcc
returns [c, i + 1]
. For the last iteration, callcc
returns nil
to break the loop.
SNOBOL4
Branches are the only kind of control structure in SNOBOL4. They come in three flavours (and one compound one):
:(LABEL_UNCONDITIONAL)
:S(LABEL_ON_SUCCESS)
:F(LABEL_ON_FAILURE)
:S(LABEL_ON_SUCCESS)F(LABEL_ON_FAILURE)
or:F(LABEL_ON_FAILURE)S(LABEL_ON_SUCCESS)
* 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
- Output:
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
SPL
In SPL jumps can be non-conditional and conditional. This is an example of non-conditional jump to label "myLabel":
myLabel ->
...
:myLabel
This is an example of conditional jump to label "4", which is done if a=0:
4 -> a=0
...
:4
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":
label 55 <->
#.output("1")
:label 55
#.output("2")
<-
and output is:
- Output:
2 1 2
SSEM
The SSEM provides two jump instructions: the absolute jump 000 <operand> to CI and the relative jump 100 Add <operand> to CI. 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 after 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:
10000000000000000000000000000000 0. 1 to CI
11001000000000000000000000000000 1. 19
and this accomplishes a relative jump forward by five words:
10000000000001000000000000000000 0. Add 1 to CI
00100000000000000000000000000000 1. 4
Tcl
Tcl has both exceptions and (from 8.6 onwards) 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 the Tcler's Wiki) so the absence is not strongly felt in practice.
TXR
TXR Lisp has a tagbody
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 go
.
When a form initiates a branch, it is gracefully abandoned, which means that unwinding takes place: unwind-protect
clean-up forms are called. Once the form is abandoned, control then transfers to the target form.
A go
transfer may be used to jump out of a lexical closure, if the tagbody
is still active. If a closure is captured in a tagbody
which then terminates, and that closure is invoked, and tries to use go
to jump to adjacent forms in that terminated tagbody, it is an error. An example of this follows, from an interactive session:
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
The above error messages reveal that TXR Lisp's tagbody
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 tagbody
is still active when the lambda tries to perform a go
, it works:
2> (let (fun) (tagbody (set fun (lambda () (go out))) [fun] (put-line "this is skipped") out (put-line "going out"))) going out nil
The translated Common Lisp example follows:
(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))
- Output:
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 ...
VBA
Public Sub jump()
Debug.Print "VBA only allows"
GoTo 1
Debug.Print "no global jumps"
1:
Debug.Print "jumps in procedures with GoTo"
Debug.Print "However,"
On 2 GoSub one, two
Debug.Print "named in the list after 'GoSub'"
Debug.Print "and execution will continue on the next line"
On 1 GoTo one, two
Debug.Print "For On Error, see Exceptions"
one:
Debug.Print "On <n> GoTo let you jump to the n-th label"
Debug.Print "and won't let you continue."
Exit Sub
two:
Debug.Print "On <n> GoSub let you jump to the n-th label": Return
End Sub
- Output:
VBA only allows jumps in procedures with GoTo However, On <n> GoSub let you jump to the n-th label named in the list after 'GoSub' and execution will continue on the next line On <n> GoTo let you jump to the n-th label and won't let you continue.
VBScript
In VBScript, there is no goto
statement. It is a good thing for structured programming.
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.
// 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)
}
}
VTL-2
VTL-2 doesn't do structured programming as such - the only control structure is the goto
.
In VTL2, everything is an assignment - including gotos - which are effected by assigning to the system variable #
.
The assigned value can be any valid expression - it need not be a constant.
If the expression evaluates to 0, the next statement is executed (or the program stops if there is no next statement).
If the expression evaluates to a line number present in the program, the program continues from that statement.
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.
The following program demonstrates this - prompiting the user for a label to goto. (In an expression, ?
indicates a value should be read from the console, assigning to ?
prints the assigned value)
1010 ?="@1010: Where to goto? ";
1020 #=?
1030 ?="@1030"
1040 #=1010
1050 ?="@1050"
1060 #=1010
2000 ?="@2000"
2010 ?="Exiting..."
- Output:
@1010: Where to goto? 0 @1030 @1010: Where to goto? 1030 @1030 @1010: Where to goto? 1041 @1050 @1010: Where to goto? 1000+50 @1050 @1010: Where to goto? 9999
Wren
Wren has three jump statements:
- break breaks out of a for or while loop
- continue (from v0.4.0) jumps to the next iteration of a for or while loop
- return returns from a function or method with or without a value.
If called from module level code, return exits the module or, if the script has only a single module, exits the script itself.
Wren also has fibers which are a bit like threads except that they are cooperatively scheduled - they only switch to another fiber when you tell them to. They are also lightweight, requiring just a small amount of memory for their stack which can be expanded if necessary.
A fiber can yield control back to the fiber that called it and be resumed later from where it left off.
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.
var func = Fn.new {
for (i in 1..10) {
if (i == 1) continue // jumps to next iteration when 'i' equals 1
System.print("i = %(i)")
if (i > 4) break // exits the loop when 'i' exceeds 4
}
for (j in 1..10) {
System.print("j = %(j)")
if (j == 3) return // returns from the function when 'j' exceeds 3
}
}
var fiber = Fiber.new {
System.print("starting")
Fiber.yield() // yields control back to the calling fiber
System.print("resuming") // resumes here when called again
Fiber.abort("aborting") // aborts the script
}
func.call() // calls the function
fiber.call() // calls the fiber
System.print("yielding")
fiber.call() // resumes the fiber
return // would exit the module (and script) without error but won't be reached
- Output:
i = 2 i = 3 i = 4 i = 5 j = 1 j = 2 j = 3 starting yielding resuming aborting [./Jump_anywhere line 17] in new(_) block argument
XPL0
XPL0 has no goto statement. The closest statements are 'return' 'exit' and 'quit', the latter being used to jump out of a 'loop' from anywhere.
The 'return' command is implied at the end of a procedure, but when explicitly written, it returns to the caller from anywhere (and from a function it returns a value).
Of course there are implied jumps in 'if' statements and in all the looping statements.
An unusual feature is the Restart intrinsic. This is like the 'exit' statement, but it restarts the program. It's sometimes simpler to restart than to unwind nested procedure calls, if for instance an error is detected.
Certain errors, such as divide-by-zero, can cause a program to exit (unless disabled by the Trap intrinsic).
If a 'jump anywhere' must be done, inline assembly code is available.
Yabasic
Yabasic supports both goto
and gosub
.
print "First line."
gosub sub1
print "Fifth line."
goto Ending
sub1:
print "Second line."
gosub sub2
print "Fourth line."
return
Ending:
print "We're just about done..."
goto Finished
sub2:
print "Third line."
return
Finished:
print "... with goto and gosub, thankfully."
end
- Output:
Igual que la entrada de FutureBasic.
Z80 Assembly
Like the 6502, the Z80 can access the entire address space of the CPU. There are no page faults, segfaults, or W^X protections on the Z80 - anything the program counter "sees" will be executed as code. Writes to read-only memory are silently ignored for the most part, but certain machines such as the Game Boy use runtime writes to ROM as a means of bankswitching, so you'll need to be familiar with your computer's documentation.
Unconditional Jumping to a Fixed Location
JP
and CALL
are the equivalents of BASIC's GOTO
and GOSUB
instructions, respectively. Both take a 16-bit memory location as their operand. The only difference between the two is that CALL
pushes the program counter onto the stack before jumping. Neither can jump to a variable location in memory; their operand must be embedded directly in the source code.
Program Counter Relative Jumps
JR
adds a signed displacement byte to the program counter. This takes one less byte to encode than a JP
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 JR
instruction and that label, and will refuse to assemble the code if the label is too far away.
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
A similar command called DJNZ
is often used for looping. It decrements the B register and jumps if and only if B is nonzero. If B is zero, the DJNZ
will do nothing and execution will move past it. Like all other jumping commands discussed so far, DJNZ
will not alter the processor flags in any way. The same distance restriction of JR
also applies to DJNZ
. This is the equivalent of the LOOP
instruction in x86 Assembly.
ld b,25
loop:
djnz loop ;loop 25 times.
The block transfer instructions LDIR
,LDDR
,OTIR
,OTDR
,CPIR
, and CPDR
all use a form of program counter relative jumping. They execute their equivalent one-time command and repeatedly jump back to it until their exit conditions are met.
Conditional Jumping
JR
,JP
,CALL
, and RET
can be made conditional based on which flags are set. Essentially these are like if
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.
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.)
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.
Jumping to a Variable Location
The incredibly misleading JP (HL)
will copy the value in the HL
register pair directly to the program counter. You would think based on the parentheses that it looks up the value stored at the memory location in HL
, but it doesn't! This is the fastest jump command the Z80 has.
JP (HL)
can be used to create a "trampoline," which lets you indirectly call a subroutine, provided that subroutine doesn't take HL
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 CALL
any address that contains either JP (HL)
or the byte 0xE9. (JP (HL)
'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 RET
, and balance the stack properly. That way, when it does RET
, it will RET
to where you were just after the CALL
.
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.
;If you're going to load it as a constant into HL you're better off just CALLing it outright.
call Trampoline
;execution will return here, with HL = address of "foo" and A = 0.
;;; somewhere away from the current program counter
Trampoline:
jp (hl)
foo:
ld a,0
ret
NB: If your hardware allows you to define the RST
calls to whatever you like, you can speed this up even more by setting one of them to JP (HL)
, and invoking that RST as your trampoline rather than the call. The only downside is that you can't conditionally execute an RST
, but if you were using a trampoline it likely wasn't going to be conditional anyway.
Another (albeit slower) way to jump indirectly is with RET
. This command takes the top two bytes off the stack and puts them directly into the program counter. It's intended for use with CALL
as a return from subroutine command, but it can also be used to go anywhere by pushing the desired memory address onto the stack and then "returning" to it. This trick is much more useful on other processors that don't have an equivalent to JP (HL)
, but on the Z80 it's not really that useful.
zkl
No gotos, just exceptions, generators, switch and the run of the mill looping constructs plus break/continue (which are limited to their loop scope). The VM has jmp instructions that the compiler uses to implement looping but those jmps are limited to function scope.
Having to hack up a goto with exceptions, state or duplicate code can be a PITA but luckily those cases seem to be rare and implementing goto could really bugger the VM state.
- Programming Tasks
- Solutions by Programming Task
- Branches
- Simple
- 360 Assembly
- 6502 Assembly
- 68000 Assembly
- 8086 Assembly
- AArch64 Assembly
- Ada
- ARM Assembly
- Arturo
- AutoHotkey
- BASIC
- Applesoft BASIC
- BASIC256
- Chipmunk Basic
- GW-BASIC
- IS-BASIC
- Minimal BASIC
- MSX Basic
- Quite BASIC
- Run BASIC
- True BASIC
- Tiny BASIC
- BQN
- C
- C sharp
- C++
- Clipper
- COBOL
- Common Lisp
- Computer/zero Assembly
- D
- DCL
- Déjà Vu
- Delphi
- EMal
- Erlang
- ERRE
- Factor
- FBSL
- Forth
- Fortran
- FreeBASIC
- FutureBasic
- Go
- Harbour
- Haskell
- I
- J
- Java
- Jq
- Julia
- Kotlin
- Lingo
- Logtalk
- Lua
- M2000 Interpreter
- Mathematica
- Wolfram Language
- MBS
- МК-61/52
- MIPS Assembly
- MUMPS
- Neko
- Nim
- Oforth
- Ol
- PARI/GP
- PascalABC.NET
- Perl
- Phix
- PicoLisp
- PL/I
- PL/SQL
- PowerShell
- PureBasic
- Python
- QBasic
- QB64
- Quackery
- Racket
- Relation
- Retro
- Raku
- REXX
- Ring
- Robotic
- Ruby
- Continuation
- SNOBOL4
- SPL
- SSEM
- Tcl
- TXR
- VBA
- VBScript
- V (Vlang)
- VTL-2
- Wren
- XPL0
- Yabasic
- Z80 Assembly
- Zkl
- ACL2/Omit
- AWK/Omit
- Bc/Omit
- F Sharp/Omit
- GUISS/Omit
- Modula-2/Omit
- Oberon-2/Omit
- UNIX Shell/Omit
- Insitux/Omit
- Pages with too many expensive parser function calls