Reputation: 175
The following is my code in assembly language to compare two numbers and print a test character to confirm if it's written correctly.
DATA SEGMENT
NUM1 DB 50
NUM2 DB 45
DATA ENDS
CODE SEGMENT
ASSUME CS: CODE, DS: DATA
START: MOV AX, DATA
MOV DS, AX
MOV AL, NUM1
MOV BL, NUM2
CMP AL, BL
JLE TAG
TAG: MOV DL, AL
MOV AH, 02H
MOV DL, 'T'
INT 21H
MOV AX, 4CH
INT 21H
CODE ENDS
END START
My assumption is, CMP will compare AL to BL. If AL is smaller, JLE will be true and the code in the part 'TAG' will be executed. As you can see AL is not smaller, still, TAG is executed.
Upvotes: 3
Views: 26659
Reputation: 39166
My assumption is, CMP will compare AL to BL. If AL is smaller, JLE will be true and the code in the part 'TAG' will be executed. As you can see AL is not smaller, still, TAG is executed.
I was a bit worried when I read this. I hope you know that the JLE
mnemonic stands for jump if less OR EQUAL. If you only need to decide about smaller (and this seems to be the case) then you would better use the jl
instruction (jump if less).
The real problem then with your code (and you already solved this yourself) is that with a construct like:
jcc label
label:
...
the code at label is always executed because
A simple way to solve this would be to insert an unconditional jump right before the label, so that in the event the condition wasn't true the code at label could be jumped over:
cmp al, bl
jl label
jmp beyond
label:
mov ah, 02h ;Executed only is AL is smaller than BL
mov dl, 'T'
int 21h
beyond:
...
An even simpler way to solve this issue is to just bypass the code at label by using the opposite conditional jump. There's also no longer need for the label itself.
For jl
the opposite conditional jump is jge
(jump if greater or equal)
For jle
the opposite conditional jump is jg
(jump if greater)
cmp al, bl
jge beyond
mov ah, 02h ;Executed only is AL is smaller than BL
mov dl, 'T'
int 21h
beyond:
...
If you treat the numbers as signed quantities, then using jl
(jump if less) and jg
(jump if greater) is the correct way.
On the other hand if the numbers are to be treated as unsigned quantities you need to use the jb
(jump if below) and ja
(jump if above) instructions.
Upvotes: 1
Reputation: 175
I solved it.
In assembly language. It goes top-down and will come across the code in the TAG section regardless of the condition being met or not. Simply adding a JMP command (before the TAG section begins) will make it go to termination directly after checking the condition to ensure it gives a logically correct answer.
Upvotes: 2