Programming Constructs
(Pseudocode) specifications will often use common, high-level programming constructs such as if
-statements or while
-loops. While most high-level languages allow for a direct translation of such specifications by offering similar constructs as part of the syntax, Assembly languages do not offer such abstractions. This page gives an overview of how to build higher-level constructs with low-level Assembly instructions.
It is important that you do not treat this page as a construction manual that you will need every time when programming Assembly. It is merely intended to help you build an intuition about the concepts, such that you can develop your skills of breaking down complex problems (i.e., high-level programming constructs) into smaller parts (i.e., Assembly instructions). Make sure you thoroughly engage with the given examples and try to understand why they work the way they are.
If-Then-Else
One of the essentials of high-level programming constructs is the if-then-else
statement. Essentially it can explained as: If a certain condition is true then do this, else do that.
Consider a higher-level (C) example of an if-then-else
:
if (n > 1) {
// ifcode
} else {
// elsecode
}
Assuming that n
is in rax
, the same construct can be built in Assembly as:
cmpq $1, %rax
jg ifcode
jmp elsecode
ifcode:
# ifcode
jmp end
elsecode:
# elsecode
end:
Note that the comparison should always be read from right to left ("rax
greater than 1") - this is due to the implementation of the compare instruction in combination with the reversal of operand order in the AT&T Syntax.
The above-shown code can even be shortened like this:
cmpq $1, %rax
jg ifcode
elsecode:
# elsecode
jmp end
ifcode:
# ifcode
end:
Loops
Equally important for many algorithms are loops. They come in many flavors (while
, do-while
, ...), however, they mostly rely on the same concepts. Below are some simple examples of loop constructs in C and their "translation" to Assembly.
Do-While
do {
// loopcode
} while (n == 1)
loop:
# loopcode
cmpq $1, %rax
je loop
While
while (n == 1) {
// loopcode
}
loop:
cmpq $1, %rax
jne end
# loopcode
jmp loop
end:
For
for (int i = 0; i < 10; i++) {
// loopcode
}
A for
-loop is essentially just a nicer way to write a certain type of while loop. It could equally be written as:
int i = 0;
while (i < 10) {
// loopcode
i++;
}
You should be able to construct the Assembly version of this yourself considering the earlier examples.
Last updated