Search code examples
assemblyx86nested-loopsirvine32

Unable to understand nested loops in assembly language


This is an exercise from assembly language for intel based computers by Irvine:

What will be the final value of EAX in this example?

   mov eax,0
   mov ecx,10     ; outer loop counter
L1:
   mov eax,3
   mov ecx,5      ; inner loop counter
L2:
   add eax,5
   loop L2        ; repeat inner loop
   loop L1        ; repeat outer loop

My solution is that eax =28 as initially ecx is set to 5, so L2 executes 5 times, so eax= 3+5*5=28. Then ecx becomes 0 and flow moves out of L2, but since ecx=0, L1 would not be repeated and it would move to the next line without repeating L1. So final value of eax=28. I know this is wrong, but can someone tell where is the fault in my thinking?


Solution

  • You are correct and there is even a bigger problem in that this code would never end.

        mov     eax, 0              ; Unnecessary as next instruction changes this
    L1: 
        mov     eax, 3
        mov     ecx, 5
    L2: add     eax, 5
        loop    L2
        loop    L1                  ; ECX is decremented first
    

    So this code would be like the Energizer Bunny and go on forever and the result would be continually 28 over and over again.

        mov     eax, 0              ; Unnecessary as next instruction changes this
    L1: push    ecx                 ; This and the pop below solves the problem
        mov     eax, 3
        mov     ecx, 5
    L2: add     eax, 5
        loop    L2
        pop     ecx
        loop    L1                  ; ECX is decremented first
    

    Now the program will at least end, but the result is still only going to be 28. If it needs to be 253 like I think the objective is, then you should be able to see the one instruction you need to move to make that happen.