Function definition: Difference between revisions

Content added Content deleted
Line 129: Line 129:
multiply:
multiply:
mul ab
mul ab
ret</lang>

=={{header|8086 Assembly}}==
A function is nothing more than a named section of code. A <code>CALL</code> instruction will push the current value of the instruction pointer and then set the instruction pointer to that address. Execution will continue forward until a <code>RET</code> statement is encountered, at which point the top of the stack is popped into the instruction pointer register. Note that the <code>RET</code> statement assumes that the top of the stack contains the actual return address, even though in reality this may not be the case. There is no validation that the return address is correct! This is why it's important for the assembly programmer to ensure the stack is balanced at all times, otherwise your program will go running off to who knows where.

It's important to remember that, unlike other languages, execution of assembly code is on a purely linear path by default, much like in other "primitive" languages like BASIC, and so there is nothing stopping the instruction pointer from "falling into" subroutines. Often this can be handy if you're trying to code a variation on a function whose only difference is doing a few extra things at the beginning, but it's something you'll need to guard against, either with a return to the operating system or an infinite loop.

<lang asm>start:
mov ax, 0x0400
mov bx, 0x0500
call sum
;at this point in execution, the AX register contains 0x0900.
;more code goes here, ideally with some sort of guard against "fallthrough" into sum.

; somewhere far away from start
sum:
add ax,bx
ret</lang>
ret</lang>