How is the most basic function pointer created in C?
Asked
Active
Viewed 285 times
-5
-
http://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work – David Ranieri Oct 01 '14 at 15:02
2 Answers
2
Here's a pretty straightforward example:
#include <stdio.h>
#include <string.h>
int add(int x, int y) {
return x + y;
}
int sub(int x, int y) {
return x - y;
}
int main() {
char const * operator = "addition";
int (*operation)(int, int) = NULL;
if (strcmp(operator, "subtract") == 0)
operation = sub;
if (strcmp(operator, "addition") == 0)
operation = add;
if (operation) {
int x = 3;
int y = 7;
int z = operation(x, y);
printf("%s %d %d == %d\n", operator, x, y, z);
}
}
Where is this useful?
A common use case that I've seen is to create interfaces. So, for example, we have a type of object, say a struct that represents a network interface. Now, because there are different hardware backend, we might want to implement the functions differently depending on the hardware implementation.
So we might have a function pointer in the interface struct for initializing the hardware, sending packets, and receiving packets.

Bill Lynch
- 80,138
- 16
- 128
- 173
0
This code will demonstrate how to create and modify a basic function pointer
#include <stdio.h>
int my_function(int);
int (*function)(int)=&my_function;
int my_function2(int x){
function=&my_function; // & is optional
return (0);
}
int my_function(int x){
function=my_function2;
return (x);
}
/* And an example call */
int main(){
printf ("%d \n",function(10));
printf ("%d \n",function(10));
printf ("%d \n",function(8));
return 0;
}

Simson
- 3,373
- 2
- 24
- 38