A for loop is a type of control flow statement that repeatedly runs a section of code until a condition is satisfied.
for (int i = 0; i < 3; ++i) {
printf("%d", i);
}
Example of a for loop that prints "012" in C
At the assembly level, for loops are implemented using conditional and unconditional jumps. The compiler translates the initialization, condition check, increment, and loop body into equivalent jump-based control flow.
<init>
loop_start:
'evaluate condition
goto end_loop if not <continue_condition>
'loop body
...
'increment and repeat
<step>
goto loop_start
end_loop:
Given the C code:
for (int i = 0; i < 3; ++i) {
// ...
}
write an equivalent for loop in assembly
.pos 0x1000
# <init>
ld $i, r0 # r0 = &i
ld (r0), r0 # r0 = i
ld $-3, r1 # r1 = 3
loop_start:
mov r0, r2 # r2 = i
add r1, r2 # r2 = i - 3 (allows us to use beq)
# evaluate condition
beq r1, end_loop # go to just after loop
# loop body
# increment and repeat
inc r0
br loop # go to start of loop
end_loop:
.pos 0x2000
i: .long 0