Write a "replace" function that replaces every character in the source string between the first occurrence of character "(" and the first following ")" with character "?". This function should return the length of the string.
Example:
before: stop playing ("the lick") all the time!
after: stop playing (??????????) all the time!
return: 39*
What I wrote looks like this:
.data
input: .space 80
prompt: .asciz "before: "
msg1: .asciz "after: "
msg2: .asciz "return: "
.text
main:
li a7, 4
la a0, prompt
ecall
li a7, 8
la a0, input
li a1, 80
ecall
li t0, 40 # '('
li t1, 41 # ')'
li t2, 63 # *
li t3, 32 # space
li t4, 10 # \n
li t5, 0 #counter
loop1:
lbu a2, (a0)
beq a2, t4, print #if string!=\n,go line exit and print
beq a2, t0, loop2#if current char !=( go line 29 else go loop2:
addi t5, t5, 1 #add 1 to the counter
jal a0
#addi a0, a0, 1 #move string to next char
j loop1
loop2:
addi t5, t5, 1 #add 1 to counter cuz '('
addi a0, a0, 1#move string to next char
lbu a2, (a0) #give current a0 address to a2
beq a2, t1, loop3 #if != ')" go line 38 ,else go loop3:
sb t2, (a0) #store current t2 to a0's address
j loop2
loop3:
addi t5, t5, 1#add 1 to counter cuz ')'
addi a0, a0, 1#move string to next char
lbu a2, (a0)
beq a2, t4, print #if current = '\n' go print
j loop3
print:
li a7, 4
la a0, msg1
ecall
li a7, 4
la a0, input
ecall
li a7, 4
la a0, msg2
ecall
li a7, 1
add a0, t5, zero
ecall
exit:
li a7, 10
ecall
But the teacher said that although it could complete the task in this way, it was not the correct process and that I needed to use 'jal' to do it. But I have no exposure to it, so please tell me what I should do.
print
seem to be incomplete. There is no return from it. The teacher might have meant that you should usejal
to call it andret
to return from it. Instead it looks like it will fall through toexit
and terminate right after. \$\endgroup\$jal
is jumping to the given location while saving the address of the next instruction inra
. Theret
instruction is jumping to the address stored inra
. So in conjunction they provide the mechanism of calling and returning from subroutines. \$\endgroup\$