200k views
5 votes
Write a C function which mimics the behavior of the assembly language function below. Note that this time, the assembly language code is recursive (despite –O2 compilation), and your C code should likewise be recursive.

f:
cmpl $1, %edi
je .L3
xorl %eax, %eax
testl %edi, %edi
jle .L7
subq $8, %rsp
subl $1, %edi
call f
testl %eax, %eax
sete %al
addq $8, %rsp
movzbl %al, %eax
.L7:
ret
.L3:
movl $1, %eax
ret

User Makan
by
4.0k points

1 Answer

7 votes

Answer:

#include <stdio.h>

int f(int edi) {

if (edi == 1) {

return 1;

}

if (edi <= 0) {

return 0;

}

edi--;

int eax = f(edi);

if(eax == 0) {

return 1;

} else {

return 0;

}

}

int main(void) {

int edi = 9;

int ret;

ret = f(edi);

printf("%d", ret);

return 0;

}

Step-by-step explanation:

  • Inside the function f, check if edi is 1 or less than 1 and then return a number accordingly.
  • Decrement the edi variable, call the f function and assign its value to eax.
  • Check if eax is equal to 0 then return 1 else return 0.
  • Inside the main function, call the f function by passing the edi value and finally display the value of ret.
User Bart De Boeck
by
4.4k points