c++到MIPS - if语句的小问题

C++ to MIPS - Small issue with if statements

本文关键字:问题 语句 if MIPS c++      更新时间:2023-10-16

c++程序:

 int main()
{
   char string[256];
   int i=0;
   char *result = NULL;  // NULL pointer 
   // Obtain string from user
   scanf("%255s", string);
   // Search string for letter t.
   // Result is pointer to first t (if it exists)
   // or NULL pointer if it does not exist
   while(string[i] != '')
   {
      if(string[i] == 't')
      {
         result = &string[i]; 
         break; // exit from while loop early
      }
      i++;
   }
   if(result != NULL)
      printf("Matching character is %cn", *result);
   else
      printf("No match foundn");
}

MIPS代码,我有:

    .globl main
        .text 
# main 
main:
        li $v0,4                # Load value 4 
        la $a0, msg0            # Load array
        syscall                 
        li $v0,8                # Load value 8
        la $a0,string           # Load array
        syscall                 # Syscall
        li $v0,4                # Load immediate value 4 
        la $a0, string          # Load array
        syscall                 # Syscall
        la $t0, string          # array    
        la $t1, result          # array
        lb $t2, result          # array
while:
        lb $t3, 0($t0)          
        beq $t3, $0, if2        # if !=0
        beq $t3, 't', if        # If = "t"
        addi $t0, $t0,1         # i++
        j while                 # Jump to While
if:
        sw $t3, result          # Save result to memory
        li $v0,4                # Load value 4 
        la $a0, found           # Load array
        syscall                 # Syscall
        j exit
        j if2                   # Jump to if2
if2:
        li $v0,4                # Load value 4 
        la $a0, notfound        # Load array
        syscall                 # Syscall
        j exit
exit: 
        li $v0, 10
        syscall # Exit
        .data
        msg0: .asciiz "Enter Word: "
        string: .byte 0:256
        i: .word 0
        result: .word 0
        found: .asciiz "Found!"
        notfound: .asciiz "Not Found"

我写的MIPS代码似乎是工作的,但我认为它不遵循上面的c++代码结构。我也认为,我搞砸了一些东西与if语句,但不能弄清楚是什么和如何修复它。有什么建议可以改进吗?

谢谢

我认为mips代码与C代码非常接近。主要区别在于,它实际上是将函数末尾的测试内联到分支中,以优化分支。While循环在汇编中往往看起来不直观。它们通常被编译成如下格式:

if(test) {
    do {
         body;
    } while(test);
}

就像@user2229152说的,你已经删除了最终检查(if(result != NULL)),并将打印移动到ifif2块。

所以你的汇编代码本质上是这样的:

while(string[i] != '')
{
   if(string[i] != 't')
   {
      i++;
   } else
   {
      result = &string[i]; 
      printf("Found!");
      goto exit;
   }
}
printf("Not found");
exit: