Implementing a flow “(1) if {…} else if {…} … (2)” in Assembly

前端 未结 2 954
北荒
北荒 2021-01-27 15:18

I have the following flow in C:

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


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


        
相关标签:
2条回答
  • 2021-01-27 15:33

    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.

    0 讨论(0)
  • 2021-01-27 15:33

    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.

    0 讨论(0)
提交回复
热议问题