c++到MIPS - if语句的小问题
C++ to MIPS - Small issue with if statements
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)
),并将打印移动到if
和if2
块。
所以你的汇编代码本质上是这样的:
while(string[i] != ' ')
{
if(string[i] != 't')
{
i++;
} else
{
result = &string[i];
printf("Found!");
goto exit;
}
}
printf("Not found");
exit:
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- Craps游戏问题,忽略if语句
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 有人能在我的代码中找到与C++中的IF语句相关的问题吗
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 如果 GPA 计算器的语句问题
- C++:关于for语句和参数的一般问题
- 为什么当我从语句检查中删除"+ mod"时,以下程序给出错误的答案。问题链接:https://www.codechef.com/problems/FFC219B
- C++字符串和 while 语句的问题
- 使用语句if时逻辑的问题
- C - 如果语句问题.代码将不会运行其他,否则
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 在设置 if-else 语句以删除特定货币并保持更新时遇到问题
- 如果/else语句未显示/可变分配问题的输出;初学者程序员
- 在循环中与开关语句有问题
- If/Else 语句在 2D 数组中移动时出现问题
- 从类模块检索信息以在 switch 语句中输出时出现问题
- 我的 IF 语句中存在问题,否则无法正常工作
- C++函数问题中的 IF 语句