HOME HTML EDITOR C JAVA PHP

C Function Pointers: Functions as Variables

A **Function Pointer** is a specialized pointer that points to the executable code of a function within the memory's code segment. This is a powerful feature used for implementing "Callbacks," designing flexible APIs, and creating dynamic code execution paths.

1. The Syntax of Function Pointers

The syntax for declaring a function pointer can be tricky. You must specify the return type and the exact parameter types of the function it will point to.

Declaration and Assignment:

// A normal function
void sayHello(int times) {
    printf("Hello %d times!", times);
}

int main() {
    // Declare a function pointer named 'ptr'
    void (*ptr)(int);

    // Assign the address of the function to the pointer
    ptr = &sayHello; // or simply: ptr = sayHello;

    // Call the function using the pointer
    (*ptr)(5); // or simply: ptr(5);
}

2. Why Use Function Pointers?

While they might seem complex, function pointers are the backbone of advanced C programming:

3. Practical Example: A Simple Calculator

Instead of using an if-else chain for operations, we can use an array of function pointers.

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

int main() {
    // Array of 2 function pointers
    int (*op[2])(int, int) = {add, sub};

    int result = op[0](10, 5); // Calls add(10, 5)
    printf("Result: %d", result);
}

4. Function Pointers vs. Data Pointers

Feature Data Pointer (int*, char*) Function Pointer
Points To Variable/Data (Stack/Heap) Executable Code (Code Segment)
Primary Use Modifying data Invoking logic dynamically
Dereferencing Returns the stored value Executes the function

5. Common Pitfalls

Pro Tip: Use typedef to make function pointer syntax much cleaner. For example, typedef int (*MathFunc)(int, int); allows you to declare pointers simply as MathFunc myPtr;.