Blog Datasheets Home About me Clients My work Services Contact

G2Labs Grzegorz Grzęda

Pointers to functions in C

April 15, 2024

Pointers to functions in C are a powerful feature that allows you to store the address of a function in a variable and use this variable to call the function. This can be particularly useful for implementing callbacks, passing functions as arguments to other functions, or creating arrays of functions. Here’s a basic rundown of how they work:

Declaring a Function Pointer

  1. Syntax: The syntax for declaring a function pointer is similar to declaring a normal pointer, but with the function’s signature. For example, if you have a function int sum(int, int), a pointer to this function is declared as int (*ptr_sum)(int, int).

  2. Initialization: You can initialize a function pointer by assigning it the address of a function with a matching signature. For example: ptr_sum = sum;.

Using a Function Pointer

Practical Examples

  1. Passing Functions as Arguments: You can pass function pointers to other functions, allowing those functions to call the passed-in functions. This is useful for creating generic functions like sorters or mappers.

  2. Arrays of Function Pointers: You can create an array of function pointers, where each element can point to a different function of the same signature. This is often used in implementing state machines or lookup tables.

Important Notes

Example Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>

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

int main() {
    // Function Pointer Declaration
    int (*ptr_add)(int, int);

    // Assigning Pointer to a Function
    ptr_add = add;

    // Using the Function Pointer
    int result = ptr_add(10, 20);
    printf("Result: %d\n", result);

    return 0;
}

This example demonstrates a simple use of function pointers. Remember, the real power of function pointers comes into play in more complex scenarios like callbacks, event handlers, and dynamic function calls.


➡️ ESP32 vs. Other Microcontrollers: Pros and Cons


⬅️ Getting Started with ESP32: A Comprehensive Guide


Go back to Posts.