Why is 0 moved to stack when using return value?

The purpose of that area is revealed by the following code

int main(int argc, char** argv)
{
    if (rand() == 42)
      return 1;

    printf("Helo World!\n");
    return 0;
}

At the start it does

movl    $0, -4(%rbp)

then the early return looks as follows

callq   rand
cmpl    $42, %eax
jne .LBB0_2
movl    $1, -4(%rbp)
jmp .LBB0_3

and then at the end it does

.LBB0_3:
movl    -4(%rbp), %eax
addq    $32, %rsp
popq    %rbp
retq

So, this area is indeed reserved to store the function return value. It doesn’t appear to be terribly necessary and it is not used in optimized code, but in -O0 mode that’s the way it works.

Leave a Comment