Search code examples
c++assemblymasmirvine32

Need assistance with loop to iteratively add to sum variable in Assembly


I'm trying to convert the following C++ code into Assembly (MASM, Irvine32):

const int SIZE = 10;

int numbers[SIZE] = {10,60,20,33,72,89,45,65,72,18};
int limit = 50;
int index = 0;
int sum = 0;

while( index < SIZE )
{
    if( numbers[index] <= limit )
    {
        sum = sum + numbers[index];         // sum += array[index];
    }
    index++;
}

If anyone could clear up where I'm going wrong -- I'm getting errors at L1: it's just spouting out "+10". I believe it's because I cannot translate sum=sum+numbers[index] into Assembly. If anyone could help me do that it would be fantastic. My attempt at translating it (lines starting from "total: mov esi, offset numbers" to "inc index") is obviously incorrect.

.data
SYZ = 10
numbers DWORD 10, 60, 20, 33, 72, 89, 45, 65, 72, 18
limit DWORD 50
index DWORD 0
sum DWORD 0

.code
main PROC
mov eax, index
mov ebx, SYZ
top: cmp eax, ebx
jae next
jb total

total: mov esi, OFFSET numbers
mov ecx, limit

cmp [esi], ecx

jbe L1

L1: add eax, ebx

inc index

jmp top

next: mov edx, sum

call WriteInt



exit
main ENDP
END main

Solution

  • Your conditional branch that implements the if is wrong. It should look like:

    top:
    ...
        cmp [esi], ecx
        ja L1               ; conditional jump *over* an ADD instruction
        add eax, [esi]      ; [esi] is array[index] if you increment ESI properly...
    L1: inc index
        jmp top
    

    In your C++, you can see that if numbers[index] <= limit then you want to update the sum, otherwise just increment the index and go back to the "top"; aka recheck the stopping condition.

    Your original asm code was doing a condition check and then continuing regardless of the result.

        cmp [esi], ecx
        jbe L1               ; jump or fall-through to L1, condition irrelevant
    L1: add eax, ebx
    

    The C++ equivalent of your original asm is:

    if( numbers[index] <= limit )
    {
    }
    
        sum += ebx;
        index++;
    

    I'm not sure if this will solve all of your problems, but it will definitely solve one of them.