🔗

Understanding Function Pointers in C

Nov 6, 2024

Function Pointer in C

Overview

  • Function pointers in C are similar to normal data pointers (e.g., int *, char *), but they point to code rather than data.
  • They store the start of executable code of a function.

Example of Function Pointer Declaration and Use

  • Basic Example: #include<stdio.h> void fun(int a) { printf("Value of a is %d\n", a); } int main() { void (*fun_ptr)(int) = &fun; (*fun_ptr)(10); return 0; } Output: Value of a is 10

Explanation

  • Brackets are necessary around function pointer declaration to avoid confusion with function returning a pointer.
  • Function pointers point to code, unlike data pointers.

Interesting Facts

  1. Function pointers point to code, unlike normal pointers that point to data.

  2. No memory allocation/deallocation is needed for function pointers.

  3. Function names can be used to get their address directly.

    • Example of simplified code without & and * operators: void (*fun_ptr)(int) = fun; fun_ptr(10);
  4. Arrays of function pointers can be created:

    void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
  5. Function pointers can replace switch-case constructs.

  6. Function pointers can be passed as arguments and returned from functions.

Practical Use Cases

  • Sorting and Searching with function pointers: int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } qsort(arr, n, sizeof(int), compare);
  • A generalized search function can utilize function pointers: int search(void *arr, int arr_size, int ele_size, void *x, bool compare(const void*, const void*))

Object-Oriented Features in C++

  • Many C++ features like virtual functions are implemented using function pointers in C.

Related Concepts

  • How to declare a pointer to a function.
  • Understanding C++ function call by pointer.
  • Difference between pointers and arrays in C.

Summary

  • Function pointers provide flexibility and capability for dynamic execution of functions in C.
  • They can help avoid code redundancy and allow for cleaner code architecture by allowing functions to be passed around and executed dynamically.