SrcForge

Lesson 23

Function Pointers

A function pointer stores the address of a function and allows it to be called indirectly at runtime. Function pointers enable dynamic function selection, callback functions, dispatch tables, and menu-driven programs. Their declaration must match the target function's return type and parameter list exactly.

C Track

Save progress as you learn.

44 lessons

Lesson content

Function Pointers in C Programming: A Complete Beginner to Advanced Guide

What are Function Pointers in C Programming?

A function pointer is a pointer that stores the address of a function instead of the address of a variable. Using a function pointer, you can call a function indirectly through its memory address.

Function pointers make programs more flexible by allowing functions to be selected and called at runtime.

For example, a calculator program can use function pointers to choose whether to perform addition, subtraction, multiplication, or division based on the user's choice.

Think of a function pointer like a remote control. Instead of pressing buttons directly on a TV, the remote stores the information needed to control different functions.

Why Do Function Pointers Exist?

Normally, function calls are fixed at compile time. Function pointers allow programs to:

  • Select functions dynamically
  • Implement callback functions
  • Build menu-driven applications
  • Create event-driven systems
  • Improve code reusability
  • Simplify large programs

Real-World Use Cases

Function pointers are widely used in:

  • Callback functions
  • Event handling
  • Device drivers
  • Operating systems
  • Interrupt handlers
  • GUI applications
  • Plugin systems
  • State machines
  • Menu-driven programs

Prerequisites

Before learning Function Pointers in C Programming, you should know:

  • Functions
  • Pointers
  • Arrays
  • Structures
  • Return types
  • Parameter passing

Core Concepts of Function Pointers in C Programming

What is a Function Pointer?

Every function in C has a memory address. A function pointer stores that address.

int add(int, int);

Function pointer:

int (*ptr)(int, int);
PartMeaning
intReturn type
(*ptr)Pointer to a function
(int, int)Function parameter list

Declaring a Function Pointer

Syntax

return_type (*pointer_name)(parameter_types);
int (*operation)(int, int);

Assigning a Function to a Pointer

A function's name automatically converts to its address in most expressions. Both of the following forms are valid:

operation = add;

operation = &add;

Calling a Function Through a Pointer

Two equivalent methods are available. The first form is more commonly used:

result = operation(5, 3);

result = (*operation)(5, 3);

Arrays of Function Pointers

You can store multiple function addresses in an array. This is useful for menu-driven applications and dispatch tables.

int (*operations[4])(int, int);

Callback Functions

A callback function is a function passed as an argument to another function and called later.

execute(add, 5, 10);

The execute() function calls add() through the function pointer it receives.

Code Examples

Example 1: Beginner – Basic Function Pointer

#include <stdio.h>                          // Include standard input/output library

int add(int a, int b)                       // Define a function
{
    return a + b;                           // Return the sum
}

int main(void)                              // Program entry point
{
    int (*ptr)(int, int);                   // Declare a function pointer

    ptr = add;                              // Store the address of add()

    printf("Result = %d\n", ptr(10, 20));   // Call the function through the pointer

    return 0;                               // End the program
}

Output: Result = 30

Example 2: Beginner – Using Multiple Functions

#include <stdio.h>                          // Include standard input/output library

int add(int a, int b)                       // Addition function
{
    return a + b;                           // Return the sum
}

int subtract(int a, int b)                  // Subtraction function
{
    return a - b;                           // Return the difference
}

int main(void)                              // Program entry point
{
    int (*operation)(int, int);             // Declare a function pointer

    operation = add;                        // Point to add()

    printf("Addition = %d\n", operation(8, 3)); // Call add()

    operation = subtract;                   // Point to subtract()

    printf("Subtraction = %d\n", operation(8, 3)); // Call subtract()

    return 0;                               // End the program
}

Example 3: Intermediate – Callback Function

#include <stdio.h>                              // Include standard input/output library

int multiply(int a, int b)                      // Multiplication function
{
    return a * b;                               // Return the product
}

int calculate(int (*func)(int, int), int x, int y) // Accept a function pointer
{
    return func(x, y);                          // Call the passed function
}

int main(void)                                  // Program entry point
{
    printf("Result = %d\n", calculate(multiply, 6, 5)); // Pass multiply() as a callback

    return 0;                                   // End the program
}

Output: Result = 30

Example 4: Intermediate – Array of Function Pointers

#include <stdio.h>                              // Include standard input/output library

int add(int a, int b)                           // Addition function
{
    return a + b;                               // Return the sum
}

int subtract(int a, int b)                      // Subtraction function
{
    return a - b;                               // Return the difference
}

int multiply(int a, int b)                      // Multiplication function
{
    return a * b;                               // Return the product
}

int divide(int a, int b)                        // Division function
{
    return b != 0 ? a / b : 0;                  // Return the quotient or 0 if division by zero
}

int main(void)                                  // Program entry point
{
    int (*operations[4])(int, int) = {add, subtract, multiply, divide}; // Array of function pointers

    printf("Addition = %d\n", operations[0](20, 5));       // Call add()

    printf("Subtraction = %d\n", operations[1](20, 5));    // Call subtract()

    printf("Multiplication = %d\n", operations[2](20, 5)); // Call multiply()

    printf("Division = %d\n", operations[3](20, 5));       // Call divide()

    return 0;                                               // End the program
}

Example 5: Advanced – Menu-Driven Calculator

#include <stdio.h>                                  // Include standard input/output library

int add(int a, int b)                               // Addition function
{
    return a + b;                                   // Return the sum
}

int subtract(int a, int b)                          // Subtraction function
{
    return a - b;                                   // Return the difference
}

int multiply(int a, int b)                          // Multiplication function
{
    return a * b;                                   // Return the product
}

int divide(int a, int b)                            // Division function
{
    return (b != 0) ? a / b : 0;                    // Return the quotient or 0 if division by zero
}

int main(void)                                      // Program entry point
{
    int choice = 3;                                 // Select an operation

    int (*operations[])(int, int) = {add, subtract, multiply, divide}; // Array of function pointers

    printf("Result = %d\n", operations[choice - 1](15, 5)); // Call the selected function

    return 0;                                       // End the program
}

Common Mistakes and Pitfalls

WrongCorrect
Declaring the pointer incorrectlyUse return_type (*ptr)(parameters)
Calling an uninitialized function pointerAssign a valid function before calling
Using incompatible function signaturesMatch the return type and parameter types exactly
Forgetting to check for NULLVerify the pointer before calling when applicable
Confusing function pointers with normal pointersRemember that they point to executable code, not data

Wrong:

int (*ptr)(int, int);

ptr(5, 10);

Correct:

int (*ptr)(int, int);

ptr = add;

printf("%d\n", ptr(5, 10));

Best Practices

  • Use meaningful names such as operation, callback, or handler.
  • Ensure the function pointer's signature matches the target function exactly.
  • Initialize function pointers before use.
  • Check for NULL before calling a function pointer when it may not be initialized.
  • Use arrays of function pointers for menu-driven programs and dispatch tables.
  • Prefer typedef to simplify complex function pointer declarations.

Using typedef makes the code easier to read and maintain:

typedef int (*Operation)(int, int);

Operation op = add;

When NOT to Use This

Avoid function pointers when:

  • A direct function call is sufficient.
  • The program logic is simple and does not require dynamic function selection.
  • The added complexity outweighs the benefits.
  • Performance-critical code cannot tolerate the small overhead of indirect function calls (on some systems).

For straightforward applications, normal function calls are usually easier to understand and maintain.

Summary / Key Takeaways

  • Function Pointers in C programming store the addresses of functions.
  • Function pointers enable indirect function calls.
  • Their declaration must match the function's return type and parameter list.
  • Function pointers are commonly used for callbacks, event handling, and dispatch tables.
  • Arrays of function pointers simplify menu-driven and state-based programs.
  • Always initialize function pointers before calling them.
  • Use typedef to improve readability when working with complex function pointer types.

FAQ About Function Pointers in C

1. What is a function pointer in C?

A function pointer is a pointer that stores the address of a function, allowing the function to be called indirectly.

2. Why are function pointers used?

They allow functions to be selected at runtime, making programs more flexible. They are commonly used for callbacks, event handling, and menu-driven applications.

3. What is a callback function?

A callback function is a function passed as an argument to another function through a function pointer. The receiving function invokes it when needed.

4. Can a function pointer point to different functions?

Yes. As long as the functions have the same return type and parameter list, a function pointer can be reassigned to point to any of them.

5. What is the advantage of using typedef with function pointers?

typedef simplifies complex function pointer declarations, making code more readable and easier to maintain.

typedef int (*Operation)(int, int);

Operation calculate = add;