Need help understanding conditional directives wit

2019-06-11 00:26发布

I am trying to implement the following c code in MASM using MASM directives:

if ( a > b )
    a = a - 1;
else
    if ( b >= c )
        b = b − 2;
    else
        if ( c > d)
            c = c + d;
        else
            d = d / 2;

This is my attempt:

.if (a > b)
sub a, 1
.elseif b >= c1
sub b, 2
.elseif c1 > d
add c1, d
.else
mov eax, d
cdq
mov ebx, 2
idiv ebx
mov d, eax
.endif
.endif

I feel like my logic is sound yet no matter what I change around to keep it intact I am getting errors. I am sure I have misunderstood something, but don't unsure about what.

1条回答
干净又极端
2楼-- · 2019-06-11 00:58

First of all, since you have only one opening .if, you only need one .endif. Second, at least if a, b, c1, and d are normal memory operands, you have a problem that most instructions can't use two memory operands (directly). For your typical comparisons, at least one of the operands most be in a register.

As an aside, I'd also indent .if (and such) code just like you normally would code in a higher level language. At least normally, I'd also use dec instead of sub x, 1, and probably shr instead of idiv to divide by 2.

Taking all of the above into account, you end up with something like this:

.model flat, c
.data
    a dd ?
    b dd ?
    c1 dd ?
    d dd ?

.code
junk proc
     mov eax, a
     mov ebx, b
     mov ecx, c1
     mov edx, d

    .if eax > ebx
        dec a
    .elseif ebx >= ecx
        sub b, 2
    .elseif ecx > edx
        add ecx, edx
        mov c1, ecx
    .else
        shr edx, 1
        mov d, edx
    .endif
junk endp

    end

This assembles just fine, at least for me.

查看更多
登录 后发表回答