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

时间:2013-04-04 20:48:36

标签: c++ mips

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] != '\0')
   {
      if(string[i] == 't')
      {
         result = &string[i]; 
         break; // exit from while loop early
      }
      i++;
   }

   if(result != NULL)
      printf("Matching character is %c\n", *result);
   else
      printf("No match found\n");
}

我拥有的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语句弄乱了一些东西但是无法弄清楚是什么以及如何解决它。有什么建议我可以改进吗?

由于

2 个答案:

答案 0 :(得分:1)

我认为mips代码非常接近C代码。它的主要区别在于它实际上将函数末尾的测试内联到分支中以优化分支。虽然循环在装配时看起来不直观。它们通常被编译成看起来更像的东西:

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

答案 1 :(得分:0)

与@ user2229152相同,您已删除最终检查(if(result != NULL))并将打印件移至ifif2块。

所以你的汇编代码基本上对应于:

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

printf("Not found");

exit: