Function Pointers in C

Function pointers are a powerful feature in C that allow for flexible and dynamic programming. They enable you to treat functions as data, passing them as arguments, storing them in arrays, and even returning them from other functions. This article will explore the various aspects of function pointers and their applications.

What are Function Pointers?

A function pointer is a variable that stores the memory address of a function. Just as we can have pointers to integers or structures, we can have pointers to functions. This allows us to call a function indirectly, through the pointer, rather than by using its name directly.

Basic Syntax

The syntax for declaring a function pointer can be a bit tricky at first. Here’s the general form:

return_type (*pointer_name)(parameter_types);

For example, a pointer to a function that takes two integers and returns an integer would be declared as:

int (*func_ptr)(int, int);

Examples of Function Pointers

1. Simple Function Pointer Usage

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

int main() {
    int (*func_ptr)(int, int) = add;
    printf("Result: %d\n", func_ptr(5, 3));  // Output: Result: 8
    return 0;
}

2. Array of Function Pointers

Function pointers can be stored in arrays, allowing for dynamic selection of functions:

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

int main() {
    int (*operations[3])(int, int) = {add, subtract, multiply};
    printf("Result: %d\n", operations[1](10, 5));  // Output: Result: 5
    return 0;
}

3. Function Pointers as Arguments

Functions can accept other functions as arguments using function pointers:

void perform_operation(int (*operation)(int, int), int a, int b) {
    printf("Result: %d\n", operation(a, b));
}

int divide(int a, int b) {
    return b != 0 ? a / b : 0;
}

int main() {
    perform_operation(divide, 10, 2);  // Output: Result: 5
    return 0;
}

4. Returning Function Pointers

Functions can also return pointers to other functions:

int (*select_operation(char op))(int, int) {
    switch(op) {
        case '+': return add;
        case '-': return subtract;
        // ... other cases ...
        default: return NULL;
    }
}

int main() {
    int (*operation)(int, int) = select_operation('+');
    if (operation) {
        printf("Result: %d\n", operation(10, 5));  // Output: Result: 15
    }
    return 0;
}