Back to: C Tutorials For Beginners and Professionals
Passing Pointer to Function in C Language with Examples
In this article, I am going to discuss Passing Pointer to Function in C Language with Examples. Please read our previous articles, where we discussed Pointer to Array of functions in C Language with Examples.
Pointer to Function in C Language
Pointers can also be passed as an argument to a function like any other argument. Instead of a variable, when we pass a pointer as an argument then the address of that variable is passed instead of the value. So any change made to the pointer by the function is permanently made at the address of the passed variable. It is also known as call by reference in C.
#include<stdio.h> int addition (); int main () { int result; int (*ptr) (); ptr = &addition; result = (*ptr) (); printf ("The sum is %d", result); } int addition () { int a, b; printf ("Enter two numbers: "); scanf ("%d %d", &a, &b); return a + b; }
Output:
Points to Remember while Passing Pointer to Function:
- A function pointer points only to code, not to data.
- Using function pointers we do not allocate de-allocate memory.
- To get a function address a function’s name can also be used.
- We can have an array of function pointers like normal pointers.
- In place of the switch case, we can use the Function Pointer.
Example to Understand Passing Pointer to Function in C Language
#include <stdio.h> void salaryhike (int *var, int b) { *var = *var + b; } int main () { int salary = 0, bonus = 0; printf ("Enter the employee current salary:"); scanf ("%d", &salary); printf ("Enter bonus:"); scanf ("%d", &bonus); salaryhike (&salary, bonus); printf ("Final salary: %d", salary); return 0; }
Output:
In the next article, I am going to discuss Character Pointer in C language. Here, in this article, I try to explain Passing Pointer to Function in C Language with Examples. I hope you enjoy this article. I would like to have your feedback. Please post your feedback, question, or comments about this article.