Monday, August 19, 2013

PROcedures

Now I'm going to talk to you about procedures. Procedures are certain pieces of code that are labeled specially. Take this example: a procedure is like a kingdom or country of it's own. Procedures can help you with what we call redundancy. Redundancy is when you have 2 pieces of code that are exactly alike so when you make a change to 1 of them you have to remember to make the same change to the other 1 and that's just such a headache!

So do you remember that program I did in my post called The powers? Well if you haven't read it yet you should before you read the rest of this post. So if you have read it do you remember how we had to raise to the next power of 3 and we did it twice? That's redundancy. Now look at my program below and notice the word proc. That stands for procedure.



.model flat, c
.stack 100h
.data
powerof3 dword 1
count dword 0
.code
doit proc
mov ecx, 3
mov ebx, 1
again:

call calculateNextPower

; Multiplying the power of 3 and the sum
mov eax,powerof3
mul ebx
mov ebx,eax

call calculateNextPower

; adding the sum and the power of 3
add ebx,powerof3

; Repeat if neccesary
cmp count,5
jl again
ret
doit endp

calculateNextPower proc
 ; Raising to the next power of 3
mov eax,powerof3
mul ecx
mov powerof3,eax
inc count
ret
calculatenextpower endp
end

How this works is there are 2 procedures and there is something  new, if you look at the program above you'll notice the word call and then calculateNextPower  well if you look right above you'll see calculateNextPower proc. 


When you call a location it's kind of like jl. You go to the location and then execute the code but then you get to the ret and this get's fun. You see when you do the call it moves the value of the instruction to the top of the stack and when you do the ret that's the same as saying pop eip which stands for instruction pointer so you move the value of the instruction after the call into the instruction pointer so you go back to where you came from.




No comments:

Post a Comment