Course Content
C Tutorial
About Lesson

Function Pointers and Callbacks

Function pointers in C are powerful and versatile entities that enable you to create callbacks and implement various functionalities within your programs. These pointers hold the address of functions, allowing you to pass functions as arguments to other functions, store them in arrays, and invoke them dynamically during runtime.

Declaring Function Pointers

To declare a function pointer, you need to specify the return type and parameters of the function it will point to. For instance:

// Declaration of function pointer
int (*funcPtr)(int, int);

Here, funcPtr is a pointer to a function that takes two int parameters and returns an int.

Assigning Functions to Pointers

Once declared, you can assign functions to these pointers. For example:

int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {
return a - b;
}

int main() {
int (*operation)(int, int); // Declare function pointer
operation = add; // Assign 'add' function to pointer

int result = operation(10, 5); // Invoke 'add' function through pointer
// 'result' will hold 15

operation = subtract; // Reassign 'subtract' function to the same pointer
result = operation(10, 5); // Invoke 'subtract' function through pointer
// 'result' will hold 5

return 0;
}

Callback Functions

Callback functions are functions passed as arguments to other functions. They allow you to customize the behavior of a function by providing different implementations at runtime.

void performOperation(int x, int y, int (*callback)(int, int)) {
int result = callback(x, y);
printf("Result: %dn", result);
}

int multiply(int a, int b) {
return a * b;
}

int main() {
performOperation(8, 4, add); // Pass 'add' function as a callback
performOperation(8, 4, multiply); // Pass 'multiply' function as a callback

return 0;
}

Benefits of Function Pointers and Callbacks

  • Flexibility: Function pointers provide flexibility by allowing dynamic function invocation.
  • Customization: Callback functions enable customization of behaviors without modifying the core function.
  • Modularity: They facilitate modular programming, separating concerns and promoting reusability