What is Function Pointer in C: Simple Explanation and Example
function pointer in C is a variable that stores the address of a function, allowing you to call the function indirectly through the pointer. It works like a remote control that points to a function instead of a TV, letting you choose which function to run at runtime.How It Works
Think of a function pointer as a remote control for functions. Instead of calling a function directly by its name, you store its address in a pointer variable. Later, you can use this pointer to call the function. This is useful when you want to decide which function to run while the program is running, not when you write the code.
In C, every function has a memory address where its code lives. A function pointer holds that address. When you use the pointer, the program jumps to that address and runs the function. This is similar to how a TV remote controls different TVs by sending signals to their addresses.
Example
This example shows how to declare a function pointer, assign it to a function, and call the function through the pointer.
#include <stdio.h> // A simple function that adds two integers int add(int a, int b) { return a + b; } int main() { // Declare a function pointer that points to a function taking two ints and returning int int (*func_ptr)(int, int); // Assign the address of 'add' function to the pointer func_ptr = add; // Call the function using the pointer int result = func_ptr(5, 3); printf("Result of add(5, 3) using function pointer: %d\n", result); return 0; }
When to Use
Function pointers are useful when you want to choose between different functions dynamically. For example, in a menu system, you can store different actions as function pointers and call the right one based on user choice. They are also used in callback functions, where you pass a function pointer to another function to be called later.
Another common use is in implementing plugins or event handlers, where the exact function to run is not known until runtime. This makes your code more flexible and reusable.
Key Points
- A function pointer stores the address of a function.
- You can call a function indirectly using its pointer.
- Function pointers enable dynamic function calls and callbacks.
- They increase flexibility by allowing runtime decisions on which function to execute.