Seek
Seek

Reputation: 107

Dividing numbers in MASM using macros?

I am trying to write a MASM macro that takes a number and divides it by two:

mCalculateDiscount MACRO originalPrice
    PUSH EDX
    PUSH ECX
    MOV  EDX, 0
    MOV  EAX, originalPrice
    MOV  ECX, 2
    DIV  ECX
    POP  ECX
    POP  EDX
ENDM

And the answer will be saved inside of EAX, is this approach wrong and what approach is right, using macros or procedures?

Upvotes: 1

Views: 164

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58518

For an operation that really boils down to a single instruction (not counting the code to load the operands), I think you would normally just write it directly, without resorting to a macro.

A macro like this is inefficient because it doesn't take into account the surrounding code. What if you didn't have any important data in EDX? Then the push/pop of EDX is a waste. Likewise for ECX. Or maybe in your surrounding code, ECX was used for something else, but ESI was available; if coding directly you could just use ESI for the divisor instead. With the macro you lose that opportunity.

If your code becomes so complex that you can't keep it organized without macros like this, then it is probably time to port it to a higher-level language like C. Your macros with built-in push/pop are doing a feeble version of register allocation, which an actual compiler can do much more effectively.

Finally, as Erik Eidt points out, using DIV to divide by two is very inefficient; you should right shift instead (probably about 10 times faster), and it also avoids needing a bunch of extra registers. This whole macro could be replaced by

    MOV EAX, originalPrice
    SHR EAX, 1

Upvotes: 2

Related Questions