Pointers and Functions

Filter Course


Pointers and Functions

Published by: Zaya

Published date: 18 Jun 2021

Pointers and Functions Photo

Pointers and Functions


In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.

#include
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf(“Value of a is %d\n”, a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of following two
void (*fun_ptr)(int);
fun_ptr = &fun;
*/
// Invoking fun() using fun_ptr
(*fun_ptr)(10);
return 0;
}

Output:
The value of a is 10
Why do we need an extra bracket around function pointers like fun_ptr in the above example?
If we remove the bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is a declaration of a function that returns a void pointer.


Following are some interesting facts about function pointers

1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
3) A function’s name can also be used to get functions’ addresses. For example, in the below program, we have removed the address operator ‘&’ in the assignment. We have also changed the function call by removing *, the program still works.

#include
void add(int a, int b)
{
printf(“Addition is %d\n”, a+b);
}
void subtract(int a, int b)
{
printf(“Subtraction is %d\n”, a-b);
}
void multiply(int a, int b)
{
printf(“Multiplication is %d\n”, a*b);
}
int main()
{
// fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;
printf(“Enter Choice: 0 for add, 1 for subtract and 2 ”
“for multiply\n”);
scanf(“%d”, &ch);
if (ch > 2) return 0;
(*fun_ptr_arr[ch])(a, b);
return 0;
}

Enter Choice: 0 for add, 1 for subtract, and 2 for multiply
2
Multiplication is 150
6) Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a function.

For example, consider the following C program where wrapper() receives a void fun() as a parameter and calls the passed function.