Type definitions
Define two types with typedef:
typedef void (*func_p)(char *name); // define function pointer type
typedef void func_t(char *name); // define function type
Using function pointer vs function type variables
Function pointer types are used more often, for example when passing callbacks as function parameters. A function type can also be used as a function parameter.
/* define a function pointer type and a function type with the same parameters */
typedef void (*func_p)(char *name); // define function pointer type
typedef void func_t(char *name); // define function type
/* define a function that matches the parameters */
void func_callback(char *name){
printf("hello,%sn",name);
}
int main(){
func_p f1 = func_callback;
func_t *f2 = func_callback;
f1("aaa");
f2("bbb");
}
Execution result:
hello,aaahello,bbb
The difference in usage shown above:
- func_p is a function pointer type, so f1 is a function pointer and can be assigned the function name directly.
- func_t is a function type, so a variable of that type must be declared with *, for example func_t *f2, so f2 becomes a function pointer and can be assigned the function name.
Function name and &function name
Assigning the function name directly is the common practice. Tests show that using the address-of operator is also valid; the resulting behavior is the same.
int main(){
func_p f1 = func_callback;
func_t *f2 = func_callback;
if (func_callback == &func_callback)
{
printf("============n");
}
f1("aaa");
f2("bbb");
}
Execution result:
============
hello,aaahello,bbb
Conclusion: function_name == &function_name. The function name, for example func_callback, can be used as a function pointer; prepending & still yields a function pointer.
Equivalent call syntax
The following call forms are equivalent:
(*f1)("aaa");
(*f2)("bbb");
Function pointer type and function type as parameters
Passing a callback into another function is normally done using a function pointer parameter:
typedef void (*func_p)(char *name); // define function pointer type
typedef void func_t(char *name); // define function type
/* define callback function */
void func_callback(char *name){
printf("hello,%sn",name);
}
/* define function that takes a function pointer type as a parameter */
void run_p(func_p fp, char *name){
fp(name);
}
/* define function that takes a function type as a parameter */
void run_t(func_t ft, char *name){
ft(name);
}
int main(){
run_p(func_callback, "PP");
run_t(func_callback, "TT");
}
Execution result:
hello,PPh hello,TT
Many compilers perform behind-the-scenes adjustments that allow passing a function name where a function type is expected. To avoid relying on implicit behavior, prefer using function pointer types explicitly when declaring parameters.
ALLPCB