Search code examples
loopsassemblymov

Assembly Count to Zero


I am trying to teach myself Assembly (out of curiosity and interest of learning) and have developed some code that counts from five to 0. Thats all it does. I was wondering if the following code was efficient?

.386
.model flat, stdcall

.data
i dd 5

.code
main:
    MOV cx, 5
    lp:
    LOOP lp
    MOVZX eax, cx  
RET 
END main

Notice that I use the MOVZX instruction to copy the value of cx into eax (what my compiler uses to return). I do this because my program won't assemble if I simply use MOV. Is using MOVZX desireable? Or is there a more efficient way I should be doing this?

You will notice also in my code that I have i dd 5 my original plan was to MOV cx, i but my compiler refuses to assemble when I attempt that. (MOVSX yields the same result). So my second question is, how can I move the value of i into the cx register?


Solution

  • If you're writing for a 32-bit target, then use the ecx register instead of the 16-bit cx register. Then, you will be able to use mov eax, ecx without the assembler complaining about operand sizes. Also, the loop instruction implicitly uses ecx so you'll want to make sure the whole register is initialised with 5, and not just the lower 16 bits.

    After using ecx, the instruction mov ecx, i may work - but you didn't say what actual error you were getting when you tried that.