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!
===== If-Then and If-Then-Else ===== Sometimes we want to execute a little piece of code only if some condition holds. And maybe we want to execute a different piece of code only if it fails. In “structured” programming languages, these constructs are called <code>if</code> and <code>if ... else</code>. Just like for loops, our lives get a little bit simpler if we ''invert'' the condition. This is the standard in assembly language programming, so really make sure you get used to that. Demorgan’s Laws can also be quite helpful. Suppose we want to read an input and output 1 if the number is 10, and zero otherwise. In a structure language, that might look like this: <syntaxhighlight lang="c">if (input == 10) { output 1 } else { output 0 }</syntaxhighlight> Let’s translate that into assembly. Firstly, we can’t do <code>== 10</code>. What we ''can'' do is <code>input - 10</code>. If the result is 0, the input was 10. <pre>move|inp|d1 # read from input to register 1 loadi|10 move|s0|d2 # get 10 into register 2 sub # compare them loadi|else jnz # jump to the else case if input was not 10 label then # fall through to here if the input was 10 loadi|1 move|s0|out loadi|done j label else loadi|0 move|s0|out label done</pre> A deeper if-elseif-else chain is implemented by simply repeating this inside the <code>else</code> block.
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)