Can anyone explain why I got -1 ???
This is undefined behavior, but possible answer is that compiler is using same register
.text
.globl factorial
.type factorial, @function
factorial:
.LFB0:
.cfi_startproc
pushq %rbp #
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp #,
.cfi_def_cfa_register 6
subq $16, %rsp #,
movl %edi, -4(%rbp) # value, value
# fact.c:14: if(value == 0) value *factorial (value - 1); so if value != 0 execute these 2 lines
cmpl $0, -4(%rbp) #, value
jne .L2 #, jump to L2 if not equal to 0
# fact.c:14: if(value == 0) value *fact (value -1); execute next 4 lines if value == 0
movl -4(%rbp), %eax # value, tmp90
subl $1, %eax #, _1
movl %eax, %edi # _1,
call factorial #
.L2:
# fact.c:17: }
nop
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
So register eax
is used for return value, thus if you look this assembly snippet:
movl -4(%rbp), %eax # value, tmp90
subl $1, %eax #, _1
movl %eax, %edi # _1,
call factorial #
You see that value
have been moved into %eax
, than 1
is subtracted and factorial
is called again in which case its value
is not 0
thus it will exit.
EAX: The accumulator. This register typically stores return values from functions.
from this page.