Kotaa
Kotaa

Reputation: 201

Implementing a flow "(1) if {...} else if {...} ... (2)" in Assembly

I have the following flow in C:

// some stuff1
//................


if (something1) {
    func1();
    func2();
} else if (something2) {
    func3();
    func4();
}

// some stuff2

I wonder, how can I encode that in Assembly? I mean, not exact intructions, but the flow. Should I use labels for jumping to what's inside if (something1) { ...} and "else if (something2)"? How would I return then to "// some stuff2"?

  ; some stuff1
  ; and then 

  cmp [some_struc], SOME_CONST
  je .... ????

  cmp [some_struc], SOME_CONST2
  je .... ????


  ; some stuff2
  ; how to better get back here?
  cmp rax, 0 

Or should I call them as functions? Then how would I skip the 2nd "else if (something2) {" if the 1st one is true?

I can implement somehow, but I want to know how to better do that.

Upvotes: 0

Views: 342

Answers (2)

Sep Roland
Sep Roland

Reputation: 39166

I would say that it largely depends on how much code you have in these {...} blocks.
If there's limited code in them use:

    cmp  [some_struc], SOME_CONST
    jne  Else
    {...}
    jmp  EndIf
Else:
    cmp  [some_struc], SOME_CONST2
    jne  EndIf
    {...}
EndIf:
    cmp  rax, 0

If there's more code:

    cmp  [some_struc], SOME_CONST
    jne  Else
    call Part1
    jmp  EndIf
Else:
    cmp  [some_struc], SOME_CONST2
    jne  EndIf
    call Part2
EndIf:
    cmp  rax, 0

Part1:
    {...}
    ret
Part2:
    {...}
    ret

Best use call. I would not advice to jump to Part1 or Part2 and then jump back to EndIf.
This creates spaghetti code. Less readable and quickly becomes less maintainable.

Upvotes: 1

Uriel Zilberberg
Uriel Zilberberg

Reputation: 119

As i see it you have two options:

  1. Use functions like you said. then all you need to do is call func. the advantage is readability and more slick code as well as automatic jump back to where you called the function, but it will cost you the overhead of using a function (setting up the registers and pushing and popping the stack pointer).
  2. Use labels. this is straightforward. But you will need to declare a label for getting back to the function, or save the return address somewhere, which affects readability.

Anyway your conditional piece of code :

cmp [some_struc], SOME_CONST2 

seems OK.

Upvotes: 0

Related Questions