【问题标题】:How to use if-else or switch operator in Assembly?如何在汇编中使用 if-else 或 switch 运算符?
【发布时间】:2020-01-14 18:35:37
【问题描述】:

如何在 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;
     }

谢谢。

【问题讨论】:

  • 为什么不创建一个包含语句的 C 程序,构建它,然后查看生成的汇编代码? Here's a good online resource 去做。
  • 通常,您使用条件跳转来适当地转移控制。具体细节取决于您想到的特定架构。
  • 这两段代码不等价,switch 已经失败,例如对于 i==2,所有打印都将被执行。
  • 你知道如何做一个 if-then 吗?如果没有,那么先学习。仅此一项就有很多细节(例如反转条件),并且可以推断到其他细节。
  • 在某些情况下,switch 语句可以更有效地作为跳转表来完成。 with switch 变量的值将作为跳转表的索引。

标签: if-statement assembly switch-statement


【解决方案1】:

架构对于细节至关重要,但这里有一些伪代码可以满足您的需求。

... # 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

【讨论】:

    【解决方案2】:

    详细的答案取决于您为其编写汇编语言的特定机器指令集。基本上,您编写汇编代码来执行 C 语言系列的测试(if 语句)和分支。

    在伪汇编中可能如下所示:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多