Conditional structures: Difference between revisions

Content added Content deleted
m (→‎{{header|6502 Assembly}}: corrected typo)
Line 153: Line 153:


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
===Branching===
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes.
6502 Assembly has 8 conditional branch instructions; each instruction will test the appropriate flag and condition and jump between -128 and 127 bytes.
To understand these conditional instructions, it is helpful to remember that the comparison instructions (CMP, CPX, CPY) set the flags as if a subtraction had occurred:
To understand these conditional instructions, it is helpful to remember that the comparison instructions (CMP, CPX, CPY) set the flags as if a subtraction had occurred:
Line 193: Line 194:
This code will loop until X is zero.
This code will loop until X is zero.
Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.
Most assemblers will figure out the correct offset for you if you use a label in place of the offset after a branch instruction, as in the above example.

===Jump Table===
A jump table is a list of subroutine addresses, which can be indexed like any other array. The 6502 has no indirect call command, but it can be created in software using an indexed jump table. One method of doing this is spoofing a return address and using the return from subroutine command to "return" to the desired subroutine.

<lang 6502asm>ReturnTable:
dw foo-1 ;each is a label to a section of code that ends in an RTS
dw bar-1
dw baz-1

ReturnSpoof: ;assume execution arrived here via a JSR command.
lda indexVariable ;contains the desired index into ReturnTable. 0 = foo, 1 = bar, 2 = baz.
asl ;the data is word length so the index must be multiplied by 2.
tax

lda ReturnTable+1,x ;get the high byte of the return address.
pha
lda ReturnTable,x ;get the low byte
pha

; Now, the desired subroutine's address minus 1 is on top of the stack.
; The RTS command will take this address and jump there. That routine's RTS command will act as the RTS from "ReturnSpoof",
; bringing execution to the point just after ReturnSpoof was called.
; If done properly, return spoofing will not corrupt the stack.

RTS ;this "RTS" acts as a JMP to the address we just put on the stack.</lang>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==