Logan Lee said:
#include <stdio.h>
#include <stdlib.h>
void func(int);
main(){
Better:
int main(void) {
void (*fp)(int);
fp = func; // here when assigning a pointer, why not fp=&func; ?
(*fp)(1);
fp(2);
exit(EXIT_SUCCESS);
}
void
func(int arg){
printf("%d\n", arg);
}
See questions 4.12 and 1.34 in the comp.lang.c FAQ,
<
http://c-faq.com/>.
A function call actually requires a function pointer value before the
parentheses. In a typical "direct" function call, this pointer value
is obtained from the name of the function.
A function name (more generally, any expression of function type) is
implicitly converted to a pointer to the function in most contexts.
(The exceptions are when it's the operand of a sizeof operator, which
is illegal rather than yielding a pointer size, and when it's the
operand of a unary "&", which yields the address of the function.)
So, in
fp = func;
the expression ``func'', which is of function type, decays to a
pointer-to-function; the result is assigned to fp.
In
(*fp)(1);
fp is of pointer-to-function type. Applying unary "*" deferences the
pointer, yielding a result of pointer type, which immediately decays
to a pointer-to-function -- which is what's required for the function
call.
In
fp(2);
fp is already of pointer-to-function type; the result is used
directly for the function call.
Note also that either
func(3);
or
(*func)(3);
is legal. (Exercise: Trace what happens in each case.)