Open main menu

CDOT Wiki β

Changes

6502 Jumps, Branches, and Procedures

1,205 bytes added, 01:31, 18 September 2023
Procedures
BEQ ; Branch on EQual (zero '''Z''' flag set)
BNE ; Branch on Not Equal (zero '''Z''' flag clear)
BMI ; Branch on MInus (negative flag '''S/N''' set) BPL ; Branch on PLus (negative flag '''S/N''' clear)
BVC ; Branch on oVerflow flag '''V''' Clear
BVS ; Branch on oVerflow flag '''V''' Set
Where $FB represents -5 in [[Signed#Two.27s_Compliment|two's compliment]] notation, since the processor needs to branch back 5 bytes from the current PC location (which is the byte after the end of the BNE instruction).
 
Because branches are always relative, code that uses only branches is called Position Independent Code (PIC) and can be easily relocated in memory. Therefore, some programmers prefer to use a forced branch instead of a jump, using an approach like this:
 
CLC ; clear the carry flag
BCC SOMEWHERE ; branch if carry clear (which will always be the case because of the previous line)
 
Although not included in the basic/original 6502, some newer variants of this processor (such as the [https://en.wikipedia.org/wiki/WDC_65C02 65C02]) have a BRanch Always (BRA) instruction which performs an unconditional relative branch.
== Procedures ==
Proedures Procedures - also called subroutines, functions, or methods - are a special case, because the program flow needs to return to the calling code when the procedure has finished.
In the 6502, the JSR (Jump to SubRoutine) instruction is used to push the current value of the [[6502#Registers|program counter]] on the stack, and then perform an unconditional jump to the address specified (using the absolute addressing mode):
To return from the procedure, the RTS (ReTurn from Subroutine) instruction loads the PC from the stack, causing execution to continue at the instruction immediately after the JSR.
 
Note that in assembly language, return values can be passed back to the calling function in registers or through stored values. In practical terms, the way that values are returned will depend on the type of data - for example, strings will generally be passed back in memory, while small integers or pointers can be passed in registers.
 
Note also that at the machine language level, there is no distinction between functions, methods, subroutines, and procedures - these distinctions apply only at the source code level and disappear during compilation to machine language.