Just like pointer to integer, pointer to structure, pointer to node in a linked list, we can declare pointer to function. Again, just declaration isn’t enough. Like other pointers, pointer to function must be initialized before indirection can be performed on it. Also, make sure that function prototype is given prior to initializing pointer to function, for without compiler would be unable to check type of function whether agreed with type of pointer to function.
Let’s consider a simple C program with pointer to function,
/* ptr2fun.c -- program declares and accesses pointer to function */ #include <stdio.h> int sum(int const, int const); int main(void) { int add_val; int (*p2f)(int const, int const) = ∑ /* p2f is a pointer to function sum */ /* calling function */ printf("sum of 5 and 5 is %d\n", sum(5, 5)); /* called by name */ printf("sum of 5 and 5 is %d\n", (*p2f)(5, 5)); /* indirection on p2f */ printf("sum of 5 and 5 is %d\n", p2f(5, 5)); /* using p2f pointer */ return 0; } int sum(int const x, int const y) { return x + y; }
When program is run, output turns out as follows,
sum of 5 and 5 is 10 sum of 5 and 5 is 10 sum of 5 and 5 is 10
Now, we count on important points in the above program. Notice the initialization of p2f,
int (*p2f)(int const, int const) = ∑ /* p2f is a pointer to function sum */
we used addressof (&) operator to initialize p2f address of function sum(). Nevertheless, operator ‘&’ isn’t necessary. Actually, compiler converts function name into function pointer which specifies where in memory function is stored.
Then, we emphasized function call statements as,
sum(5, 5); (*p2f)(5, 5); p2f(5, 5);
Which of these statements is more efficient than others? Let’s see how these internally implement. First statement calls the function by name. Compiler, as we know, converts function name into function pointer which locates where function sum() is stored in memory. Then function call operator invokes and starts executing instructions at that address.
In second function call, indirection is performed on the p2f, which results in function name sum. Compiler now converts function name to function pointer and executes as above. Actually, indirection isn’t required here.
The third statement is more efficient as this is pointer to function and executes as above.
Now, where we require pointer to functions is where we need to pass functions as arguments to some other functions. Two most common applications are callback functions and jump tables. We’ll discuss them later.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Apply for C Internship
- Check C Books