Please help me translate this nested for loop to assembly

for(int i=0, k=0; i<8; i=i+4, k++){
			for(int j=i; j<=i+4; j++){
6 Years
Discussion Span
Last Post by Schol-R-LEA

please just ignore line 3. i just need to know how to convert the for loop structure to assembly


For a single for() loop, the x86 instruction set has a special LOOP instruction.

mov ecx, 5
; the code here would be executed 5 times
loop start_loop

(Example taken from here.)

However, that has a number of serious drawbacks, with the most serious one being that it really isn't suited for nested loops (it uses CX as the counter, which if you have more than one loop means you have to somehow save the CX value before entering the inner loop and then restore it afterward).

A more solution is simply to use ordinary conditional branches. Here's a fairly typical example, which has a simple optimization of moving the test to the end of the loop (which avoids an unneeded unconditional branch on each pass):

; initialize the counter variable
    mov counter, 0
; jump to the conditional test
    jmp for_test

    ; add the body of the loop here
    ; increment the counter before going into the test
    inc counter
    cmp counter, target
    jl for_loop

This is untested code, but should work.


thanks! however, i'm having a problem with the multiple variables in my for loop. my inner for loop needs the value of i, which is declared in my outer for loop. also, k is needed in my inner for loop statement. when i tried working this out in assembly, it seems like the registers are not enough to store all my variables. T_____T


No, they probably wouldn't be; the x86 is notorious for it's relatively small register set. You can, however, use a memory variable for this purpose instead, either by a define-byte or by setting up an activation record on the stack.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.