Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

loops - Code executes condition wrong?

Basic question here,

I wrote the following block:

    IDEAL
    MODEL small
    STACK 100h
    DATASEG

    Var1 db 4
    Var2 db 2

    CODESEG

start:
    mov ax, @data
    mov ds, ax
    xor ax, ax
    mov al, [Var1]
    cmp al, [Var2]
    jg  Var1Greater
    mov ax, 1
Var1Greater:
    mov ax, 0

I'm new to assembly.

I wanted to create a code that compares [Var1] to [Var2].

IF(!) [Var1] is greater than [Var2], execute mov ax, 1. IF(1) anything else(equal or less) excecute, mov ax, 0.

How can this be done? the code I wrote executes both instructions if the condition is true.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ah, Turbo Assembler "Ideal" mode; It has been a while since I last saw it. I love Ideal mode. It is so much better thought-out and it makes so much more sense than Microsoft Assembler's syntax.

Well, what is happening is that both instructions get executed.

First, mov ax, 0 gets executed, and then control falls through to the next statement, which is mov ax, 1, so what you are left with in ax is 1.

Labels in assembly language do not magically cause control to jump elsewhere. They do not cause the assembler to emit any instructions. They only exist so that you can indicate the target of another jump instruction.

So, what you need is:

    ...
    cmp al, [Var2]
    jg  Var1Greater
    mov ax, 0
    jmp skip
Var1Greater:
    mov ax, 1
skip:

also, it is good form when writing assembly language to use xor ax, ax instead of mov ax, 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...