Lesson 3 of 8
Control flow in assembly
- 16 min
- 6 checks
- 3 hints
- Go to task
Goal
Compare and jump instead of if and loops
Explanation
Assembly has no if statement and no while loop, only a comparison followed by a jump. The cmp a, b instruction compares the two and stores the result in flags inside the CPU, and the conditional jump after it reads those flags: either it jumps to a label, or execution continues to the next line.
jgjumps if the first is greater, andjleif it's less than or equal.jejumps if the two are equal, andjneif they differ.jmpalways jumps, with no condition.
These jumps treat the numbers as signed, meaning they take into account that a number may be negative, and they have unsigned counterparts such as ja and jb. When you look at assembly, the first question to ask is when it jumps, because compilers usually emit a jump that skips over the body of an if when its condition is false, so the jump carries the opposite condition:
h: cmp edi, 10 jle .small mov eax, 1 ret .small: mov eax, 0 ret
So jle .small means: if x is less than or equal to ten, go to .small and return 0; otherwise continue to the next line and return 1.
A loop is a jump backward. In this function, eax holds the sum and ecx holds the counter. The instruction xor eax, eax is the shorthand compilers use to zero a register, and inc adds one. The jg .done jump takes you out of the loop once the counter exceeds n, and jmp .top takes you back to its start:
loop_sum: xor eax, eax ; eax = 0 mov ecx, 1 ; ecx = 1 .top: cmp ecx, edi jg .done ; ecx > n add eax, ecx ; eax += ecx inc ecx ; ecx += 1 jmp .top .done: ret
Before you write anything, think about what the loop does when n is zero or negative. The assembly is what counts, not the function's name or what you expect it to do.
Your task
Write the function h(x) that returns 1 if x is greater than ten and 0 otherwise, and the function loop_sum(n) that matches the loop above in every case, including zero and negative numbers.
Checks
6 checks- h returns 1 for values above ten
- h returns 0 for ten itself
- h matches the assembly on many numbers
- loop_sum adds up 1 through n
- loop_sum works on other values
- loop_sum returns 0 for a negative number, as the loop does