Monash University > School of Computer Science and Software Engineering > CSE1303 > Part B > Lectures > Lecture B14 notes
# Program that uses a function.
.text
main: # Read int.
li $v0, 5
syscall
move $t0, $v0
# Pass parameter in $a0.
move $a0, $t0
# Calculate ($t0)!.
jal fact # Do call.
# Put result in $t1.
move $t1, $v0
# Print factorial.
li $v0, 1
move $a0, $t1
syscall
# Exit
li $v0, 10
syscall
|
# Factorial function.
fact: li $v0, 1 # For result.
# Repeat until parameter
# is <= 1.
loop: ble $a0, 1, end
# Multiply result by
# parameter.
mul $v0, $v0, $a0
# Decrement parameter.
sub $a0, $a0, 1
# Lather, rinse, repeat.
j loop
# At end, $v0 contains
# factorial.
end: jr $ra # Return.
|
/* C program which calls a
function. */
#include <stdio.h>
#include <stdlib.h>
int power(int b, int e);
int main()
{
int base;
int exp;
int result;
scanf("%d", &base);
scanf("%d", &exp);
result = power(base, exp);
printf("%d", result);
exit(0);
}
|
.text
main: # 3 * 4 = 12 bytes local
move $fp, $sp
subu $sp, $sp, 12
li $v0, 5
syscall
sw $v0, -12($fp) # base
li $v0, 5
syscall
sw $v0, -8($fp) # exp
# Call function.
# push 2 * 4 = 8 bytes
# of arguments
subu $sp, $sp, 8
# arg 1 = base
lw $t0, -12($fp) # base
sw $t0, 0($sp) # arg 1
# arg 2 = exp
lw $t0, -8($fp) # exp
sw $t0, 4($sp) # arg 2
# Call power function
jal power
# Remove arguments, they
# are no longer needed.
# 2 * 4 = 8 bytes.
addu $sp, $sp, 8
# Store return value
# in result.
sw $v0, -4($fp) # result
# Print result.
li $v0, 1
lw $a0, -4($fp) # result
syscall
li $v0, 10 # exit
syscall
|
/* A function that gets called. */
int power(int b, int e)
{
int result = 1;
/* Keep going while exponent
is positive. */
while (e > 0)
{
/* Multiply by base. */
result = result * b;
/* less to multiply. */
e--;
}
/* Return the result
to the caller. */
return result;
}
|
power: # Save $ra and $fp.
subu $sp, $sp, 8
sw $ra, 4($sp)
sw $fp, 0($sp)
# Copy $sp to $fp
move $fp, $sp
# Alloc local variables.
# 1 * 4 = 4 bytes.
subu $sp, $sp, 4
# Initialize locals.
li $t0, 1
sw $t0, -4($fp) # result
# Now we are inside
# the function body.
loop: # Stop if e <= 0.
lw $t0, 12($fp) # e
ble $t0, 0, end
# result = result * b
lw $t0, -4($fp) # result
lw $t1, 8($fp) # b
mul $t0, $t0, $t1
sw $t0, -4($fp) # result
# e--
lw $t0, $t0, 12($fp) # e
sub $t0, $t0, 1
sw $t0, $t0, 12($fp) # e
# Repeat loop.
j loop
end: # Now ready to return.
# Return result in $v0.
lw $v0, -4($fp) # result
# Remove local var.
addu $sp, $sp, 4
# Clean up stack
lw $fp, 0($sp)
lw $ra, 4($sp)
addu $sp, $sp, 8
# Return to caller.
jr $ra
|
Last modified 2002-12-05