Function Pointer as Argument in C
Function Pointer as Argument :
The function itself cannot be passed as an argument to another function.However, by utilising a function pointer, we can pass the reference to a function as a parameter.As the function parameter is supplied as a pointer that contains the address of arguments, this technique is known as a call by reference. .
Syntax :
(type) (*pointer_name)(parameter);
Example :
Run
#include<stdio.h> //function to display even numbers int help(void (*show)()) { for(int i=0;i<=10;i+=2) { show(i); } return 0; } //printing the value void print(int val) { printf("%d ",val); } int main() { void (*show)(int); printf("The even values are :"); help(print); return 0; }
Output :
The even values are :0 2 4 6 8 10
What Happened Above ?
In the above Program, we write two function to help to find even number and print to print the numbers and use function arguments in the main function.
Point to remember for Function Pointer as Argument in C :
Point to Remember
If any change made by the function using pointers, then it will also reflect the changes at the address of the passed variable.
Example :
Run
#include<stdio.h> // function to swap two integer void help(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int val1 = 15, val2 = 30; help(&val1, &val2); //passing values to function printf("value of val1 = %d\n", val1); printf("Value of val2 = %d", val2); return 0; }
Output :
value of val1 = 30 Value of val2 = 15
What Happend Above?
In the above program, we swap two numbers using function pointer as arguments.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment