Как использовать if-else или переключать оператора в сборке? - PullRequest
0 голосов
/ 14 января 2020

Как использовать несколько операторов if-else или оператора switch из C / C ++ в Assembly?

Примерно так: C:

if ( number == 2 )
  printf("TWO");
else if ( number == 3 )
  printf("THREE");
else if ( number == 4 )
  printf("FOUR");

Или с помощью switch:

switch (i)
     {
        case 2:
           printf("TWO"); break;
        case 3:
           printf("THREE"); break;
        case 4:
           printf("FOUR"); break;
     }

Спасибо.

Ответы [ 2 ]

0 голосов
/ 14 января 2020

Подробный ответ будет зависеть от конкретного набора машинных инструкций, для которого вы пишете язык ассемблера. По сути, вы пишете код на ассемблере для выполнения серии тестов на языке 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
0 голосов
/ 14 января 2020

Архитектура имеет решающее значение для специфики, но вот некоторый псевдо-код, который делает то, что вы хотите.

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