rasz
rasz

Reputation: 43

How to avoid goto and jump when coding in assembly?

I'm aware of the numerous posts here and elsewhere on avoiding goto in high-level programming languages. However from the (admittedly small) experience I've had coding in MIPS assembly, there doesn't seem to be an obvious way to avoid goto and jump statements in assembly when implementing control flow.

For example how would this code be implemented in assembly (C equivalent):

if (x < 2)
  { ans = 0; }
else
  { ans = 1; } 

Would the use of a goto or jump statement be necessary, or is there a proper way of avoiding them in favor of more appropriate code practices?

Upvotes: 4

Views: 7229

Answers (4)

rcgldr
rcgldr

Reputation: 28826

Although it's not MIPS, for X86 processors, in the case of Microsoft assemblers ML.EXE (16 / 32 bit) and ML64.EXE (64 bit), since MASM 6.11, and all version of Visual Studio, you can use the dot directives:

ans     equ     eax

        .if     x < 2
        mov     ans,0
        .else
        mov     ans,1
        .endif

In this example, the dot directives translate into compare immediate, jump instructions, and move immediate. For more information, see

http://msdn.microsoft.com/en-us/library/8t163bt0.aspx

Upvotes: -1

dimitar kolev
dimitar kolev

Reputation: 11

When you are pressured by everyone to not use goto in high level languages, it is (kind of) understandable to not use goto. But to carry that over to assembly... It is completely impossible to not use jmp while coding in assembly, because there aren't theese hidden goto instructions like for or while.

Upvotes: 1

Sam Liao
Sam Liao

Reputation: 46043

You can't avoid using jump intruction completely, because you are already almost talking with processor directly.

But with better practice you are applying with high-level programming, you are still able to use less jumps in your assembly code.

Some ideas like:

  • Jump inside blocks, not between blocks.
  • Jump in a simple and readable logic following traditional for/while/if/case sequence.
  • One block of assembly do one thing; minimal side effect.
  • Try to use macro or function, don't repeat yourself.

Upvotes: 3

Nils Pipenbrinck
Nils Pipenbrinck

Reputation: 86363

The recommendation to avoid goto in high-level programming languages only applies to - well - high-level languages.

Assembler is a low-level language and jumps are essential.

Upvotes: 17

Related Questions