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.
As you have seen on the page about Instructions, there is a wide variety of conditional branching instructions, of which almost all are based on some processor flags. Almost all high-level programming constructs depend on conditional branching.
While technically only a small subset of the available branch instructions would be needed to offer the same functionality, the wide selection allows for more concise Assembly code. So, do not worry if you don't understand some of the conditions - you will likely not use most of them.
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
:
Assuming that n
is in rax
, the same construct can be built in Assembly as:
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:
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
While
For
A for
-loop is essentially just a nicer way to write a certain type of while loop. It could equally be written as:
You should be able to construct the Assembly version of this yourself considering the earlier examples.
Last updated