I wrote the following C program:
#include "stdio.h"
__declspec(noinline) void DivideTest(int num, int denom)
{
int quo = num / denom;
int rem = num % denom;
printf("Quotient: %d\nRemainder: %d\n", quo, rem);
}
int main(int argc, char* argv[])
{
//Use volatile variables to prevent result from being hardcoded.
volatile int num = 20;
volatile int denom = 3;
DivideTest(num, denom);
return 0;
}
As expected, the output is as follows:
Quotient: 6
Remainder: 2
However, when I compile in release mode (i.e. with optimizations enabled), debug the program in Visual Studio, and look at the disassembly, it shows DivideTest using a two-operand idiv:
_DivideTest:
push esi
mov esi,edx
mov eax,ecx
cdq
idiv eax,esi
Disassembling using dumpbin produces the same result. But every source I’ve found (
example) says that idiv can only take one operand.
When I try to assemble code using a two-operand idiv, it fails, as I would expect based on the documentation. Why does the disassembly show a two-operand idiv?
>Solution :
The disassembly is technically wrong. It just shows how idiv works. The idiv instruction always uses eax (in fact edx:eax pair) to get the dividend from and to store the result (quotient and remainder).