Need help understanding conditional directives with MASM

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 09:39:37

问题


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:


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.



来源:https://stackoverflow.com/questions/8583772/need-help-understanding-conditional-directives-with-masm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!