2

I am very new to MASM and assembly, and I am writing my first program. I am having trouble figuring out how to add two variables together and output the result. Here is part of my program so far:

 INCLUDE Irvine32.inc

 .data
 firstNum   DWORD   ?
 secondNum  DWORD   ?   
 sum        DWORD   ?       

 .code
 main PROC

 ;Get Data

 call      ReadInt
 mov       firstNum, eax
 call      ReadInt
 mov       secondNum, ebx

 ;Calculate Sum

 mov       eax, firstNum
 mov       ebx, secondNum
 add       eax, ebx
 mov       sum, eax

 ;Display Results 

 mov       eax, sum
 call      WriteDec

When I run this code, it outputs some long number "333420163" instead of what the sum should be, which is 7. I am still very new to this so if it's a simple answer I'm sorry haha. What am I doing wrong?

rkhb
  • 14,159
  • 7
  • 32
  • 60
Conman97
  • 43
  • 7
  • 1
    I don't know irvine, but `mov secondNum, ebx` can't be correct, if `mov firstNum, eax` was. If "ReadInt" returns the read value into EAX, the 2nd move should be `mov secondNum, eax` – Tommylee2k Jan 23 '17 at 08:11
  • Thank you, I was confused because I thought that if I moved the secondNum into eax it would replace the first variable. I'm still not quite sure how these registers work. It worked after I did what said! – Conman97 Jan 23 '17 at 08:30
  • "mov" works the other way round. if you write "mov variable, eax" then eax's content is moved INTO this memory, not FROM there ;-) Obviously "ReadInt" retuns the value in EAX, after storing this value in firstNum, EAX is free to be used again – Tommylee2k Jan 23 '17 at 08:37
  • Awesome! If I knew this site was so easy to get answers from helpful people like you I would have been asking questions ages ago haha – Conman97 Jan 23 '17 at 08:45
  • 1
    You should learn to use a debugger, as well. Executing your code step by step in a debugger would have allowed you to find the answer to your question yourself. – David Hoelzer Jan 23 '17 at 11:12

1 Answers1

1

On most x86 ABIs, return values for functions are typically in the EAX register, and, in the case that a return value is 64-bits long, instead of 32-bits, the upper 32-bits will be in the EDX register.

Your instructions:

call      ReadInt
mov       secondNum, ebx

Are not getting the return value from the second call to ReadInt because it is not in EBX; it's in EAX.

Replace it with mov secondNum, eax, because that will put the actual return value from ReadInt into secondNum.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 1
    It's even easier: if the first call to `ReadInt` returns the result in `EAX`, the second call will surely do so, too. – zx485 Jan 24 '17 at 09:41