Translate using if (...) goto, and goto for cmpl, conditional jumps and unconditional jumps.
Note: Introduce some names for the parameter(s) and local variables to make the code closer to C and easier to follow.
For example,
-
Use variable name ret for %eax - which will contain the return value.
-
Use variable name n for the parameter - [first parameter is always at 8(%ebp)]
f: pushl %ebp ret is %eax movl %esp, %ebp n is 8(%ebp) cmpl $0, 8(%ebp) jge .L2 if (n >= 0) goto L2 movl 8(%ebp), %eax ret = n addl $1, %eax ret++ jmp .L3 goto L3 .L2: L2: cmpl $0, 8(%ebp) jle .L4 if (n <= 0) goto L4 movl 8(%ebp), %eax ret = n subl $1, %eax ret-- jmp .L3 goto L3 .L4: L4: movl $0, %eax ret = 0 .L3: L3: popl %ebp ret return ret
Function call | Returned value |
---|---|
f(5) | |
f(-5) | |
f(0) |