Loops execute a block of code until some condition is met. The two most common types of loops are for and while. The jumps and conditional jumps that you have seen so far have been jumping forward. The loops jump backward. First, let's understand the functionality of a for loop. The general form of a for loop is shown here:
for (initialization; condition; update_statement ) {
block of code
}
Here's how the for statement works. The initialization statement is executed only once, after which the condition is evaluated; if the condition is true, the block of code inside the for loop is executed, and then the update_statement is executed.
A while loop is the same as a for loop. In for, the initialization, condition, and update_statment are specified together, whereas in a while loop, the initialization is kept separate from the condition check, and the update_statement is specified inside the loop. The general form of a while loop is shown here:
initialization
while (condition)
{
block of code
update_statement
}
Let's try to understand how the loop is implemented at the assembly level with the help of the following code snippet from a simple C program:
int i;
for (i = 0; i < 5; i++) {
}
The preceding code can be written using a while loop, as shown here:
int i = 0;
while (i < 5) {
i++;
}
We know that a jump is used to implement conditionals and loops, so let's think in terms of jumps. In the while and for loops, let's try to determine all the situations when the jumps will be taken. In both cases, when i becomes greater than or equal to 5, a jump will be taken, which will transfer the control outside of the loop (in other words, after the loop). When i is less than 5, the code inside the while loop is executed and after i++ backward jump will be taken, to check the condition.
This is how the preceding code is implemented in assembly language (shown as follows). In the following assembly code, at ➊, notice a backward jump to an address (labeled as while_start); this indicates a loop. Inside of the loop, the condition is checked at ➋ and ➌ by using cmp and jge (jump if greater than or equal to) instructions; here, the code is checking if i is greater than or equal to 5. If this condition is met, then the jump is taken to end (outside of the loop). Notice how the less than (<) condition in C programming is reversed to greater than or equal to (>=) at ➌, using the jge instruction. The initialization is performed at ➍, where i is assigned the value of 0:
mov [i],0 ➍
while_start:
cmp [i], 5 ➋
jge end ➌
mov eax, [i]
add eax, 1
mov [i], eax
jmp while_start ➊
end:
The following diagram shows the C programming statements and the corresponding assembly instructions:
