Toggle search
Search
Toggle menu
notifications
Toggle personal menu
Editing
Basic Assembly Programming
(section)
From Turing Complete
Views
Read
Edit
Edit source
View history
associated-pages
Page
Discussion
More actions
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===== A Simple Loop (partial Storage Cracker spoilers) ===== Let’s write a program that starts with 0, and then repeatedly adds 1 and keeps repeating that until the result is 0 again. We store the value <code>1</code>, which we need repeatedly, in register 2 ''outside'' of the loop, because we don’t need to re-compute it every time. Then we perform the addition, check the value, and, if it’s not zero, move the result to register 1 so that we can keep going. Notice how we have to go out of our way to move the result of the addition back into register 1 with <code>move|s3|d1</code>. The ''loop body'', or the part of the loop between the label and the jump back to the label, is written to expect that the values to add are already in registers 1 and 2. This is called a ''loop invariant''. It is fact about the state of the machine that ''must'' be true on both entry to and exit from the loop body. It’s very important to think about your loop invariants when writing loops. As the loop body becomes more complicated, failing to maintain the invariants (called ''violating'' the invariant) is a major source of bugs. If you document the invariants well, these bugs are easy to catch! <pre>loadi|1 # set up register 2 move|s0|d2 # with the value 1 label loop # the next instruction is the start of the loop add # register 3 = register 1 + register 2 loadi|done # register 0 = address of the instruction after the loop jz # jump out of the loop if the result of addition is 0 move|s3|d1 # register 1 = the result of addition loadi|loop # load the address of the first loop instruction j # and jump to it. label done</pre> That’s not so bad! But we can do a bit better. <span id="a-better-loop-layout"></span>
Summary:
Please note that all contributions to Turing Complete are considered to be released under the Creative Commons Attribution-ShareAlike (see
TuringComplete:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)