Function Pointer

Take this C code as example:
// this is defined globally.
void fun1()
// These lines are part of some function
void (*fptr)() = fun1;
Generated assembly code:
movl	$fun1, 12(%esp)
movl	12(%esp), %eax
call	*%eax
Location of local variables of the stack (local variables are explained here)
fptr => 12(%esp)
The use of registers as temporary memory is described here
Comments on generated assembly code:
# fptr = fun1
    movl    $fun1, 12(%esp)

# tmp = fptr
    movl    12(%esp), %eax

# call the function using pointer i.e. tmp()
    call    *%eax

NOTE: Here register esp is being used to refer to the local variables instead of ebp. This is up to the compiler to either use esp or ebp to index into the stack.


Want to learn (C/C++ internals) directly from the author using video call? Learn more

Do you collaborate using whiteboard? Please try Lekh Board - An Intelligent Collaborate Whiteboard App