如何在Assembly中使用多个if-else语句或C / C ++中的switch运算符?
在C中是这样的:
if ( number == 2 )
printf("TWO");
else if ( number == 3 )
printf("THREE");
else if ( number == 4 )
printf("FOUR");
或使用开关:
switch (i)
{
case 2:
printf("TWO"); break;
case 3:
printf("THREE"); break;
case 4:
printf("FOUR"); break;
}
谢谢。
体系结构对于细节至关重要,但是这里有一些伪代码可以满足您的要求。
... # your code
jmp SWITCH
OPTION1:
... # do option 1
jmp DONE
OPTION2:
... # do option 2
jmp DONE
Option3:
... # do option 3
jmp DONE
SWITCH:
if opt1:
jmp OPTION1
if opt2:
jmp OPTION2
if opt3:
jmp OPTION3
DONE:
... #continue your program
详细答案将取决于您为其编写汇编语言的特定机器指令集。基本上,您编写汇编代码来执行C语言系列测试(如果语句)和分支。
在伪汇编中,它可能看起来像这样:
load r1, number // load the value of number into register 1
cmpi r1, 2 // compare register 1 to the immediate value 2
bne test_for_3 // branch to label "test_for_3" if the compare results is not equal
call printf // I am ignoring the parameter passing here
... // but this is where the code goes to handle
... // the case where number == 2
branch the_end // branch to the label "the_end"
test_for_3: // labels the instruction location (program counter)
// such that branch instructions can reference it
cmpi r1, 3 // compare register 1 to immediate value 3
bne test_for_4 // branch if not equal to label "test_for_4"
... // perform printf "THREE"
branch the_end // branch to the label "the_end"
test_for_4: // labels the instruction location for above branch
cmpi r1, 4 // compare register 1 to immediate value 4
bne the_end // branch if not equal to label "the_end"
... // perform printf "FOUR"
the_end: // labels the instruction location following your 3 test for the value of number