Syntax of function pointers
What you'll learn: How to decipher and write the unique declaration syntax required to store a function's address in a variable.
The "Address" of Logic
Up to this point, you have used pointers to store the addresses of variables—pieces of data like integers or characters. However, in C, functions also live in memory. Every function you write has a starting address. A function pointer is simply a variable that stores that starting address, allowing you to "hold" a function in your hand and pass it around your code.
The syntax for declaring these pointers looks intimidating at first because it feels "inside out."
Deciphering the Formula
To point to a function, your pointer must exactly match the function's signature (its return type and its parameters). Here is the template:
return_type (*pointer_name)(parameter_types);
Let’s look at a concrete example. Suppose we have a simple addition function:
int add(int a, int b) {
return a + b;
}
To create a pointer that can point to add, we write:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
// 1. Declare the function pointer
// Read as: "ptr is a pointer to a function taking two ints and returning an int"
int (*ptr)(int, int);
// 2. Assign the address of the function
ptr = &add; // You can also just write: ptr = add;
// 3. Call the function using the pointer
int result = ptr(10, 20);
printf("Result: %d", result); // Outputs 30
return 0;
}
Why the Parentheses Matter?
The most crucial part of the syntax is (*ptr). The parentheses around the asterisk and the name are mandatory.
If you wrote int *ptr(int, int);, C would think you are declaring a normal function named ptr that returns a pointer to an integer. By wrapping (*ptr) in parentheses, you are telling the compiler: "This variable itself is the pointer." Think of it as a protective bubble that ensures the "pointer-ness" attaches to the name before the function arguments do.
Once declared, you treat the pointer name just like the original function name to execute the code it points to.
Key takeaway
A function pointer's declaration must mirror the target function's return type and arguments, with the pointer name wrapped in parentheses: return_type (*name)(args).