Reputation: 73
I am working on an assignment for my class. My C++ code calls the _Divide
function to take in 2 values to divide and return into 'Result'. To start I move -1 into eax. Once I'm done with the process, my eax keeps returning '-1' as the value. What could I be doing wrong? Here's my assem code:
public _Divide
.386
.model flat
.code
_Divide proc
mov eax, -1
mov ebx, 1
cdq
idiv ebx
ret
_Divide endp
end
Here's my C++ code
#include <iostream>
using namespace std;
extern "C" long Divide (long, long, long *);
void main ()
{
long Result;
long Remainder;
long Dividend;
long Divisor;
do {
cout << "Enter Dividend" << endl;
cin >> Dividend;
cout << "Enter Divisor" << endl;
cin >> Divisor;
Result = Divide (Dividend, Divisor, &Remainder);
cout << "Result is " << Result << " and Remainder is " << Remainder << endl;
} while ((Result >= 0) || (Remainder != 0));
Result = Divide (Dividend, Divisor, 0);
cout << "Result is " << Result << " and Remainder is not used" << endl;
}
Thanks.
Upvotes: 1
Views: 4148
Reputation: 225272
Your code divides -1
by 1
. The answer is -1
, so that's what you return. Let's break down the code (I'll just put inline comments):
mov eax, -1 ; Put -1 in eax
mov ebx, 1 ; put 1 in ebx
cdq ; sign extend eax -> edx:eax = -1
idiv ebx ; divide edx:eax (-1) by ebx (1)
; result goes in eax, so now eax = -1
ret ; return eax (-1) to caller
If you want to divide arguments passed to this function, you need to access them somehow. You didn't show us the C++ function signature, so I can't help you with any more details than that.
Hint: If you're writing IA32 code, which it looks like you're doing, the arguments will be on the stack.
Upvotes: 4
Reputation: 60115
If you want to write function in assembly you should learn about calling conventions first: http://en.wikipedia.org/wiki/X86_calling_conventions . Basically calling convention is the set of agreement between caller and function on how they will pass and return values.
Usual convention for C++ is usually __cdecl
or __stdcall
. Both require return value to be passed via EAX
. Since EAX
always have -1 this is what you get.
Upvotes: 2