Friday, April 4, 2014

Loops in Assembly

There are 3 types of loops in most programming languages:

1. for loop
2. while loop
3. do-while loop

For loop looks something like this:
(JS example)

for (var x=0;x<10;x++){
 doSomething();
}

While loop:

while (x<10) {
  doSomething();
  x += 2;
}


 Do-while loop:
do{
  doSomething();
  x += 3; 
} while (x<10); 

So how do we construct the loops in assembly?
Well, assembly relies on branches (jumps).
Essentially to "loop" the CPU jumps back to a specific instruction and resume running from that point again.

Following are examples of how to construct a loop in assembly:
For loop:

push ecx
mov ecx, 0x00000000
->
//doSomething()
inc ecx
cmp ecx, 0x0000000a
jl short ->
pop ecx

While loop:

push ecx
jmp short =>
->
//doSomething()
add ecx, 0x00000002
=>
cmp ecx, 0x0000000a
jl short ->
pop ecx

Do-while loop:

push ecx
->
//doSomething()
add ecx, 0x00000003
cmp ecx, 0x0000000a
jl short ->
pop ecx

Please remember stack balance. . . STACK BALANCE!!!!!! 

Ready for Easter

[placeholder for an Easter surprise]
heheheh. . .

Oh dear I seem not to be working on my Flash Engine anymore. . . :(