C Function Pointer

1. What is a Function Pointer?

  • A function pointer is a pointer that points to the address of a function instead of a variable.

  • It allows you to call a function indirectly and is useful for callbacks, dynamic dispatch, and tables of functions.


2. Syntax of Function Pointer

return_type (*pointer_name)(parameter_list);

Example:

int (*funcPtr)(int, int);
  • funcPtr → pointer to a function that takes two int parameters and returns int.


3. Example: Basic Function Pointer

#include <stdio.h>

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

int main() {
int (*funcPtr)(int, int) = &add; // pointer to function

int result = funcPtr(5, 10); // call function using pointer
printf("Result = %d\n", result);

return 0;
}

Output:

Result = 15

You can also write funcPtr = add; without &, and funcPtr(5,10) works fine.


4. Function Pointer as Callback

  • You can pass a function pointer as an argument to another function.

#include <stdio.h>

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

void operate(int x, int y, int (*op)(int, int)) {
printf("Result = %d\n", op(x, y));
}

int main() {
operate(5, 10, add); // calls add(5,10)
operate(5, 10, multiply); // calls multiply(5,10)
return 0;
}

Output:

Result = 15
Result = 50

Function pointers are widely used in callbacks and event-driven programming.


5. Array of Function Pointers

  • You can store multiple function pointers in an array:

#include <stdio.h>

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

int main() {
int (*operations[2])(int, int) = {add, subtract};

printf("Add: %d\n", operations[0](10, 5));
printf("Subtract: %d\n", operations[1](10, 5));

return 0;
}

Output:

Add: 15
Subtract: 5

6. Key Points About Function Pointers

  1. Declared as: return_type (*pointer_name)(parameter_list);.

  2. Can point to any function with matching signature.

  3. Used to call functions indirectly.

  4. Useful for callbacks, dynamic function selection, and event handling.

  5. Can be stored in arrays for tables of functions.

  6. Can pass as function arguments to other functions.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *