Reputation: 11
I'm new to assembly language and I have no idea why my conditional statement is not performing how I want it to. How I think it should work is when I use cmp on eax and -1 the program should jump to the label nonnegative when input is 0 or greater and should exit the program if less than 0, but no matter the input, the program always jumps to the label nonNegative and performs the code assigned to that label. I am using Irvine32.
INCLUDE Irvine32.inc
.data
testing BYTE "you have entered a non-negative number! ", 0
.code
main PROC
call ReadInt
cmp eax, -1
JG nonNegative
nonNegative:
mov edx, OFFSET testing
call WriteString
call CrLf
exit
main ENDP
END main
I expect program to print "you have entered a non-negative number!" for any non-negative number and I expect the program to exit for any negative number. instead the program always prints "you have entered a non-negative number!" and then exits.
Upvotes: 0
Views: 42
Reputation: 29022
You have this code:
call ReadInt ; Read the value to EAX
cmp eax, -1 ; determine JMP condition
JG nonNegative ; JMP if EAX > -1
nonNegative: ; Jump @target
mov edx, OFFSET testing ; Print message
call WriteString ; ...
call CrLf ; Print NextLine
The problem is that you correctly compare the returned value in EAX to -1
with
cmp eax, -1 ; determine JMP condition
And you correctly execute a conditional JMP with
JG nonNegative ; JMP if EAX > -1
But your mistake is that the JMP target of this jump is the next line:
nonNegative: ; Jump @target
So either if the JUMP is taken (condition fulfilled) or not taken (condition not fulfilled), the following instructions are executed:
mov edx, OFFSET testing ; Print message
call WriteString ; ...
call CrLf ; Print NextLine
Hence you always get the same result on the console:
you have entered a non-negative number!
To provide you a correct alternative, have a look at this code:
.data
negNumber BYTE "you have entered a negative number! ", 0
zeroOrAbove BYTE "you have entered a non-negative number! ", 0
.code
call ReadInt ; Read the value to EAX
cmp eax, -1 ; determine JMP condition
JG nonNegative ; JMP if EAX > -1
; this execution path was missing in your solution
mov edx, OFFSET negNumber ; Print message
call WriteString ; ...
call CrLf ; Print NextLine
jmp fin
nonNegative: ; Jump target
mov edx, OFFSET zeroOrAbove ; Print message
call WriteString ; ...
call CrLf ; Print NextLine
fin:
Upvotes: 1