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
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 asint (*ptr_sum)(int, int)
.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
- Calling a Function through Pointer: You can use the function pointer to call the function it points to. This is done using the dereference operator
*
and the function call syntax. For example:int result = (*ptr_sum)(5, 3);
. Alternatively, you can call it directly asint result = ptr_sum(5, 3);
since the function call operator()
has higher precedence than the dereference operator*
.
Practical Examples
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.
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
Type Safety: Ensure that the function signature of the pointer matches the function it points to. Mismatched signatures can lead to undefined behavior.
NULL Pointers: Just like normal pointers, function pointers can be
NULL
. It’s good practice to check if a function pointer isNULL
before calling it.Pointer Arithmetic: Unlike regular pointers, doing arithmetic on function pointers (like
ptr_sum + 1
) is not meaningful and should be avoided.
Example Code
|
|
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.