Function pointer as argument in C Language
Categories: C language
Till now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments. If any change made by the function using pointers, then it will also reflect the changes at the address of the passed variable.
Therefore, C programming allows you to create a pointer pointing to the function, which can be further passed as an argument to the function. We can create a function pointer as follows:
(type) (*pointer_name)(parameter);
In the above syntax, the type is the variable type which is returned by the function, *pointer_name is the function pointer, and the parameter is the list of the argument passed to the function.
Let's consider an example:
float (*add)(); // this is a legal declaration for the function pointer
float *add(); // this is an illegal declaration for the function pointer
A function pointer can also point to another function, or we can say that it holds the address of another function.
float add (int a, int b); // function declaration
float (*a)(int, int); // declaration of a pointer to a function
a=add; // assigning address of add() to 'a' pointer
In the above case, we have declared a function named as 'add'. We have also declared the function pointer (*a) which returns the floating-type value, and contains two parameters of integer type. Now, we can assign the address of add() function to the 'a' pointer as both are having the same return type(float), and the same type of arguments.
Let's see a simple example of how we can pass the function pointer as a parameter.
void display(void (*p)())
{
for(int i=1;i<=5;i++)
{
p(i);
}
}
void print_numbers(int num)
{
cout<<num;
}
int main()
{
void (*p)(int); // void function pointer declaration
printf("The values are :");
display(print_numbers);
return 0;
}
In the above code,
1. We have defined two functions named 'display()' and print_numbers().
2. Inside the main() method, we have declared a function pointer named as (*p), and we call the display() function in which we pass the print_numbers() function.
3. When the control goes to the display() function, then pointer *p contains the address of print_numbers() function. It means that we can call the print_numbers() function using function pointer *p.
4. In the definition of display() function, we have defined a 'for' loop, and inside the for loop, we call the print_numbers() function using statement p(i). Here, p(i) means that print_numbers() function will be called on each iteration of i, and the value of 'i' gets printed.