汇编中复杂的 IF 语句

问题描述 投票:0回答:2

我应该如何在汇编中写出这样的

if
语句?

if ((a == b AND a > c) OR c == b) { ...

平台:Intel 32位机,NASM语法。

更新

对于变量类型和值,使用更容易理解的内容。我想整数对我来说效果很好。

if-statement assembly conditional-statements x86
2个回答
25
投票

在通用组装中,它基本上是这样的(

a
中的
ax
b
中的
bx
c
中的
cx
):

    cmp  bx, cx
    jeq  istrue
    cmp  ax, cx
    jle  isfalse
    cmp  ax, bx
    jeq  istrue
isfalse:
    ; do false bit
    jmp  nextinstr
istrue:
    ; do true bit

nextinstr:
    ; carry on

如果没有错误位,可以简化为:

    cmp  bx, cx
    jeq  istrue
    cmp  ax, bx
    jne  nextinstr
    cmp  ax, cx
    jle  nextinstr
istrue:
    ; do true bit

nextinstr:
    ; carry on

11
投票

您需要将 if 语句分解为一系列比较和跳转。就像在 C 语言中一样,你可以这样写:

int test = 0;

if (a == b) {
  if (a > c) {
    test = 1;
  }
}

// assuming lazy evaluation of or:
if (!test) {
  if (c == b) {
    test = 1;
  }
}

if (test) {
  // whole condition checked out
}

这会将复杂的表达式分解为组成部分,您的汇编也会这样做,尽管您可以通过跳转到仍然相关的部分来在汇编中更清晰地编写它。

假设 a、b 和 c 在堆栈上传递给您(如果它们显然没有从其他地方加载它们)

        mov     eax, DWORD PTR [ebp+8] 
        cmp     eax, DWORD PTR [ebp+12] ; a == b?
        jne     .SECOND                 ; if it's not then no point trying a > c 
        mov     eax, DWORD PTR [ebp+8]
        cmp     eax, DWORD PTR [ebp+16] ; a > c?
        jg      .BODY                   ; if it is then it's sufficient to pass the
.SECOND:
        mov     eax, DWORD PTR [ebp+16]
        cmp     eax, DWORD PTR [ebp+12] ; second part of condition: c == b?
        jne     .SKIP
.BODY:
        ; .... do stuff here
        jmp     .DONE
.SKIP:
        ; this is your else if you have one
.DONE:
© www.soinside.com 2019 - 2024. All rights reserved.