Function Pointers in C
Function Pointers in C
Function Pointers in C
Function Pointers in C
Function Pointers point to code like normal pointers. In functions pointers, the
function's name can be used to get function's address. A function can also be passed
as an argument and can be returned from a function.
Declaration Syntax
Example
void hello(){
printf("Hello World");
}
We can now call the function with the help of this function pointer "(*ptr)();".
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 1/6
6/16/24, 1:04 PM Function Pointers in C
#include <stdio.h>
// Defining a function
void hello() { printf("Hello World"); }
return 0;
}
Output
When you run this code, it will produce the following output −
Hello World
Note: Unlike normal pointers which are data pointers, a function pointer points
to code. We can use the name of the function as its address (as in case of an array).
Hence, the pointer to the function hello() can also be declared as follows −
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 2/6
6/16/24, 1:04 PM Function Pointers in C
return a + b;
}
To declare a function pointer for the above function, we use two arguments −
We can then call the function through its pointer, by passing the required arguments
−
Here is the complete code. It shows how you can call a function through its pointer −
#include <stdio.h>
int main(){
return 0;
}
Output
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 3/6
6/16/24, 1:04 PM Function Pointers in C
When you run this code, it will produce the following output −
Addition of x: 10 and y: 20 = 30
We have a swap() function that interchanges the values of "x" and "y" with the help
of their pointers −
To swap the values of "x" and "y", pass their pointers to the above function pointer −
(*ptr)(&x, &y);
#include <stdio.h>
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 4/6
6/16/24, 1:04 PM Function Pointers in C
int main(){
(*ptr)(&x, &y);
printf("Values of x: %d and y: %d after swap", x, y);
return 0;
}
Output
We can use the property of dynamically calling the function through the pointers
instead of if-else or switch-case statements. Take a look at the following example −
#include <stdio.h>
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 5/6
6/16/24, 1:04 PM Function Pointers in C
int main(){
return 0;
}
Output
Result: 150.00
https://www.tutorialspoint.com/cprogramming/c_function_pointers.htm 6/6