Pointer to functions

Function Pointers in C

One of the powerful features of C is the ability to define pointers to functions.

  • A function pointer is a variable that stores the address of a function.

  • Like other pointers, function pointers can be declared, assigned, and used to call the function they point to.


Declaring Function Pointers

The general syntax for declaring a function pointer is:

return_type (*function_pointer_name)(argument_type1, argument_type2, ...);

Example:

int (*fp)(float, char);
  • fp is a function pointer that points to a function taking one float and one char argument and returns an int.


Initializing Function Pointers

  • Function pointers must be initialized before use.

  • Assign the function’s name (without parentheses) to the pointer:

fptr = add; // assigns address of function add to fptr

Example: Using Function Pointers

#include <stdio.h> int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int main() { int (*fptr)(int, int); // declare function pointer fptr = add; // point to add function printf("%d\n", fptr(2, 3)); // calls add(2,3) fptr = sub; // point to sub function printf("%d", fptr(3, 2)); // calls sub(3,2) return 0; }

Output:

5 1

Key Points:

  1. Function pointers allow dynamic selection of functions at runtime.

  2. Useful for implementing callback functions and table-driven programs.

  3. Can point to any function with a matching signature (return type and parameters).

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays