Answer in brief
A function pointer identifies a function with a compatible type and allows that function to be selected or passed as a value.
Declaration and assignment
int (*operation)(int, int) = add;
Meaning
operation can identify a function receiving two ints and returning int. The function name add supplies a suitable function pointer in this expression. Calling operation(4, 6) or (*operation)(4, 6) invokes the selected function. The function must have a compatible type; an arbitrary cast does not make an incompatible call safe.
Callback-style example
apply receives a function pointer named op along with a and b. It returns op(a, b). main supplies add for one call and subtract for another. Thus apply keeps the general calling step while the caller chooses the operation. The output is 10 for addition and -2 for subtraction.
Uses
- Select an arithmetic operation or menu action.
- Let a general algorithm call a caller-supplied comparison or processing function.
- Keep a table of compatible operations when that makes the design clearer.
Precautions
Do not call a null or invalid function pointer. An object pointer and a function pointer are not interchangeable portable storage formats. The sample always passes real functions with exactly matching signatures.
Complexity
An indirect call does not change the algorithmic growth of the selected function. With the fixed-size addition or subtraction shown, each application takes O(1) time and O(1) extra space. More complex callbacks can perform more work.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int apply(int (*op)(int, int), int a, int b)
{
return op(a, b);
}
int main(void)
{
printf("Add = %d\n", apply(add, 4, 6));
printf("Subtract = %d\n", apply(subtract, 4, 6));
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Add = 10
Subtract = -2
Related exam questions
Related questions in the pointer function arguments category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
View this category in the exam question bank →