Complete notes on function pointer in C or say pointer to function in C programming – Example of declaration, typedef, real time uses as callback function with program examples. Real life use of call back function is extracted from one of the real product scenario as a pseudo code.
Function pointer in C
Function pointer is a pointer variable that point to a function. In other word, pointer to function. This is similar to other data type pointers e.g. int *, char *, float* etc. that store address of variables. Function pointer in C also contains the address of a function and the function is called using function pointer. that’s simple.
lets see function pointer syntax of declaration, initialization and invocation that point to a function void msg() as an example
function pointer declaration
void (*pToMsg)()
function pointer initialization ( assign address of function msg() to function pointer).
pToMsg = &msg; or pToMsg = msg;
ampersend is optional before function name.
function pointer Invokation:
pToMsg();// invoke from main program or any functions in C program.
lets read the complete simple function pointer program to show how to declare function pointer and call pointer to function in C, also read comments.
Consider a function msg() that print hello. Declare a pointer to msg() function and pass it as an argument to another function called displayMsg. Call msg function using pointer inside the displayMsg.
Since, msg function declaration is like void msg(void), so the function pointer declaration of pointer to function msg would be “ void (*funcptr)(void) “,
Simple function pointer C program example
#include<stdio.h>
//This function will be passed to other
//function using pointer to function.
void msg()
{
printf("hello");
}
//It will recieve msg function ponter and
//execute msg function.
void displayMsg(void (*f)()){
f();
}
int main()
{
//------------First way----------
//create a pointer to msg function and
//assigne address of msg then pass to
//displayMsg function.
void (*pToMsg)();//function pointer declaration
/* the ampersand is actually optional */
//Assign function address
pToMsg = &msg;
//pass msg functin using pointer
displayMsg(pToMsg);
//-------------Second way--------------------
//Pass address of msg function directly to displayMsg
displayMsg(msg);
return 0;
}
Function pointer declaration in C
Demonstration of function pointer declaration in C for various functions that have different function prototypes.
function: void foo(int a, int b) – Accept two int arguments and return nothing.
function pointer : void (*foo)(int,int);
function: int foo(int) – Accept one int argument and return int value.
function pointer: int (*foo)(int);
Function pointer typedef in C
Function pointer typedef declaration is used to ease the reading of the code. if we typedef the declaration of function pointer as given below, we can create an alias of it and use the same in program.
typedef void (*pointerToFunc)();
In the program, rather that using void (*pointerToFunc)(), we can use it by making a variable like pointerToFunc ptr;
We use it in the same way we would use the original type, for example,
typedef int myinteger;
typedef char *mystring;
typedef void (*myfunc)();
And in the program, we use them like
myinteger i; // is equivalent to int i; integer value
mystring s; // is the same as char *s; char pointer
myfunc f; // same as void (*f)(); function pointer
See the below example to understand
#include<stdio.h>
typedef void (*pointerToFunc)();
void msg()
{
printf("hello");
}
void displayMsg(pointerToFunc p){
p();
}
int main()
{
//create function pointer
pointerToFunc ptr;
ptr = &msg;
displayMsg(ptr);
return 0;
}
Returning a function pointer in C
We can return a function pointer in C program. In below program, function pointer is typedef and has been used as a return type in function f() that return function f1 or f2 on the condition of input char ‘1’. for example, pointerToFunc f( char c ){}
#include<stdio.h>
typedef int (*pointerToFunc)();
int f1() {
return 1;
}
int f2() {
return 2;
}
//Returns function pointer
pointerToFunc f( char c ) {
if ( c == '1' ) {
return f1;//return f1()
}
else {
return f2;//return f2()
}
}
int main()
{
char c = '1';
pointerToFunc fp = f( c );
int a = fp();
printf("Val = %d",a);
return 0;
}
Use of function pointer in C
Function pointer can be used to implement a call back function in C program. Lets understand use of call back function with an example and pseudo code that I had implemented in a read software product.
Scenario – We had used callback function in a library (dll), to provide network status to the client applications, so, we can distribute the library with documents to multiple clients. And clients applications can have their own function naming convention and pass it to the callback function resides in the library to get the network status.
For example, clients functions can be BMWGetNetworkStatus() or PanasonicGetNetworkStatus() etc. Note that whatever be the client function name, we don’t have to change the code in the library to provide the status, and that should be working for every clients.
The main advantage of using callback function is to decouple the client code and library code.
Here we will see the simple pseudo code example of callback with program in C.
In below source code, assume that NetworkService() is in the dll and BMWGetNetworkStatus function in client code main().
In NetworkService() function, on the basis of random number generated ,the client function BMWGetNetworkStatus function will be called with status value continuously, and on depending upon the status number, the client function will print the value. this is the working example. You can copy the complete code and see the output in your editor. Note that this is pseudo code and don’t need to create dll but just need to copy in one program
#include<stdio.h>
#include<Windows.h>
#include<stdlib.h>
void NetworkService(void (*networkStatus)(int)){
int networkStaus =0;
while(1){
Sleep(2000);
//generate randam number
networkStaus = rand() % 5;
networkStatus(networkStaus);
}
}
/*Client main program have a function BMWGetNetworkStatus
*and pass this function to library function Network Service
*/
void BMWGetNetworkStatus(int status)
{
switch (status)
{
case 1:
printf("Connceting...");
break;
case 2:
printf("Sending...");
break;
case 3:
printf("Recieving...");
break;
default:
printf("Disconnecting...");
break;
}
}
//Client program for callback
int main(){
void (*pToMsg)(int)= &BMWGetNetworkStatus;
NetworkService(pToMsg);
return 0;
}
NOTE:
Misconception :
Q) What is difference between function pointer and pointer to function in C language?
Answer, In fact, there is no difference between them in C. function pointer and pointer to function are same.
Q) What is function to pointer?
Answer: There is no concept of function to pointer in C language. Some people says int *foo() is a function to pointer. This is wrong. In fact, foo() is a function returning a pointer.