Conditional structures: Difference between revisions

m
Line 4,298:
=={{header|MIPS Assembly}}==
MIPS is a bit unusual in that it doesn't have "flags" per se. Every branch instruction takes one or more registers as an operand and does the comparison there.
===If/Else===
 
<lang mips>BEQ $t0,$t1,Label ;branch to label if $t0 = $t1. If not, fallthrough to the instruction after the delay slot.
nop ;branch delay slot</lang>
Line 4,329:
 
Like most assembly languages, the label operand of a branch instruction is a hardware abstraction that allows you to more easily tell the assembler where you want the branch to go without having to figure it out yourself. In reality, the actual operand that the label represents is not an absolute address, but a calculated signed offset that is added to the program counter. Therefore there is a limit on how far away you can branch. Given that MIPS is a 32-bit CPU at a minimum, the maximum distance is very generous and you're extremely unlikely to ever need to branch further than it allows.
 
===Switch===
As usual, the easiest way to implement <code>switch</code> is with a lookup table, be it a table of function pointers or just a simple array. The example below is a bit abstract but you should get the idea.
 
<lang mips>switchExample:
;this implementation assumes that all destinations end in jr ra, so you'll need to arrive here with JAL switchExample.
;$t0 = index (must be a multiple of 4 or the program counter will jump to a location that's not guaranteed to properly return.)
la cases,$t1
addiu $t1,$t0 ;MIPS can't do variable indexed offsetting so we have to add the offset ourselves.
lw $t8,($t1) ;dereference the pointer, $t8 contains the address we wish to "call"
nop
jr $t8 ;jump to the selected destination.
nop
 
cases:
.word foo
.word bar
.word baz
 
foo:
;code goes here
jr ra
 
bar:
;code goes here
jr ra
 
baz:
;code goes here
jr ra</lang>
 
If you're going to do this for real, you'll want some sort of bounds check on the index. That way, if the cases are out of bounds you can conditionally change the index to the address of your default case.
 
=={{header|МК-61/52}}==
1,489

edits