I want to understand how a pointer to function works and how the functions are called in C.
In this example:
#include <stdio.h>
void invoked_function();
int main(void) {
void(*function)();
function = invoked_function;
function(); //First way to call invoked_function
(*function)(); //Second way to call invoked_function
return 0;
}
void invoked_function() {
printf("Hi, I'm the invoked function\n\n");
}
I call the function invoked_function using function(); and (*function)();, both work actually.
If the first one contanis the memory address of invoked_function, and the second contains the first byte of the code of invoked_function, why are working both?
invoked_function". No. That would be true iffunctionwere a pointer-to-char. But it's not, it's a pointer-to-function. Sofunctionis the pointer, and*functionis the function, and(*function)()is the logical way to call it. But since there's not much you can do with a function pointer except call it, when you writefunction(), without the*, the compiler (for once in its tiny, narrow-minded life) says, "Oh, okay, I guess you're trying to call the pointed-to function, so that's what we'll do."