0
.386
.MODEL FLAT, stdcall
.STACK 4096

ExitProcess PROTO, dwExitCode:DWORD

.data
arr1 DWORD 25, 89, 49, 80 
arr2 DWORD 30, 100, 50, 150 

.code
_main PROC
    sub eax, eax
    add eax, [arr1 + 0]
    add eax, [arr1 + 4]
    add eax, [arr1 + 8]
    add eax, [arr1 + 12]

    INVOKE ExitProcess, 0
_main ENDP

END

When I took out sub the sum of adding the values in the array was wrong but I don't understand why. To my understanding sub eax, eax clears the register but I could be wrong. I was told to use something like movsx instead of sub but isn't movsx only used when going between different data type sizes?

Locke
  • 7,626
  • 2
  • 21
  • 41
  • 2
    Yes it's used to zero. Since you are adding to it, and the initial value is otherwise unknown (not necessarily zero) you will probably get a wrong result if you do not zero it. You can of course `mov eax, 0` or `xor eax, eax` or even just replace the first `add` with a `mov`. – Jester Jun 30 '22 at 23:46
  • 2
    Jester's last: should use `mov` for the first memory opcode, and eliminate the clearing of the register. No need to add the first element to 0, when you can just load it instead. – Erik Eidt Jun 30 '22 at 23:48
  • 1
    Indeed, `movsx` should only be used when widening narrow data, and only *can* be used at all when the source operand is 8 or 16-bit. `mov eax, [arr1 + 0]` is somewhat like `movsx`, except it doesn't need to do any extension. – Peter Cordes Jul 01 '22 at 04:19
  • 2
    Re: what `sub eax,eax` is doing: [What is the best way to set a register to zero in x86 assembly: xor, mov or and?](https://stackoverflow.com/q/33666617) - in C terms it's like `int sum = 0;` instead of `int sum; /* uninitialized */`. Registers can (and do) hold non-zero garbage at the top of `_main`; use a debugger to see. – Peter Cordes Jul 01 '22 at 04:20

0 Answers0