🔴 Advanced · Lesson 35
Function Pointers
Function Pointers
What is Function Pointer?
A function pointer stores the address of a function. It can be used to call a function dynamically, pass functions as arguments and implement callbacks.
Syntax
Syntax
return_type (*pointer_name)(parameter_types); int (*fp)(int, int); // pointer to a function taking two int and returning int
Calling Function Pointer
C Language
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*fp)(int, int);
fp = add;
printf("Sum = %d", fp(10, 20));
return 0;
}Sum = 30
Callback Example
C Language
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
void calculate(int x, int y, int (*operation)(int, int)) {
printf("Result = %d\n", operation(x, y));
}
int main() {
calculate(10, 5, add);
calculate(10, 5, sub);
calculate(10, 5, mul);
return 0;
}Result = 15
Result = 5
Result = 50
Summary
- Function pointer stores function address
- Syntax uses parentheses:
int (*fp)(int,int) - Function name itself represents its address
- Useful for callback, menu, sorting and event handling
- Read function pointer declarations carefully from inside out
Function Pointer क्या है?
Function pointer किसी function का address store करता है। इसके द्वारा function को dynamically call कर सकते हैं और callback बना सकते हैं।
Syntax
C Language
return_type (*pointer_name)(parameter_types); int (*fp)(int, int);
Call करना
C Language
int add(int a, int b) { return a + b; }
int (*fp)(int, int) = add;
printf("%d", fp(10, 20));Callback Example
C Language
void calculate(int x, int y, int (*op)(int, int)) {
printf("%d", op(x, y));
}सारांश
- Function pointer function का address store करता है
- Syntax में parentheses important हैं
- Function name address represent कर सकता है
- Callback और menu based programs में useful है
- Declaration को carefully पढ़ें