Function Pointer as Argument in C

A function pointer as an argument allows you to pass a function to another function. This enables a high level of flexibility and modularity in your code, as you can change the behavior of a function dynamically by passing different functions as arguments.

Definition

In C, you can pass function pointers as arguments to other functions. This allows the called function to invoke the passed function. Function pointers as arguments are commonly used in callback mechanisms, event-driven programming, and sorting algorithms where you want to define custom behavior that can change at runtime.

The syntax for passing a function pointer as an argument to another function is:

Syntax:

                        
return_type function_name(return_type (*pointer_name)(parameter_types), parameter_types);
                        
                    

Example: Function Pointer as Argument

This example demonstrates how to pass a function pointer as an argument to another function to perform operations on numbers.

Example Code:

                        
#include <stdio.h>
        
// Function that performs an operation on two integers
int add(int a, int b) {
    return a + b;
}
        
int subtract(int a, int b) {
    return a - b;
}
        
// Function that takes a function pointer as an argument
int calculate(int (*operation)(int, int), int x, int y) {
        return operation(x, y); // Call the function passed as argument
}
        
int main() 
{
    int result;
        
    // Pass 'add' function pointer
    result = calculate(add, 10, 5);
    printf("Addition: %d\n", result);
        
    // Pass 'subtract' function pointer
    result = calculate(subtract, 10, 5);
    printf("Subtraction: %d\n", result);
        
    return 0;
}
                        
                    

Output

Addition: 15
Subtraction: 5

Key Points