Okay, so imagine you're at a party and you want to play a game with your friends. But instead of telling them what game you want to play, you just point to one of games and say "Hey, I pick this game!" That's basically what a function pointer is.
In programming, functions are like games. They're a set of instructions that do something. And just like at a party, sometimes you don't know exactly which function you want to use ahead of time. That's when you use a function pointer.
A function pointer is just a way to tell your program which function to use at runtime. Instead of calling a specific function directly, you can point to it with a pointer and say "Hey, you function, you're up!"
First up, let's meet our three games: add, sub, and mul. These are functions that are supposed to add, subtract, and multiply two numbers. But do they really? Let's see:
int add(int a, int b)
{
return a + b;
}
int sub(int a, int b)
{
return a - b;
}
int mul(int a, int b)
{
return a * b;
}
Now, let's see how we can use our games. We're going to create an array of function pointers that will allow us to easily call our games whenever we need them. Here's how we do it:
int (*fptr[3])(int, int) = {add, sub, mul};
Wait, what? That looks like a bunch of gibberish! Let's break it down. We are creating an array called fptr that can hold three function pointers.
The
int (*fptr[3])(int, int)part is just telling C that we're creating an array of function pointers that return anintand take twointarguments.The
{add, sub, mul}part is initializing our array with the addresses of our three games.
Now that we have our array of function pointers, we can easily call our games like this:
int res = fptr[0](5, 3); // calls the add function with arguments 5 and 3
See how easy that was? We just called our friend add with two arguments and stored the result in a variable called res. We could also call our other games like this:
int res2 = fptr[1](5, 3); // calls the sub function with arguments 5 and 3
int res3 = fptr[2](5, 3); // calls the mul function with arguments 5 and 3
See how easy that was? With a function pointer, you can switch between different functions on the fly, just like you can switch between different games at a party. So the next time you're at a party and you want to play a game, just remember: function pointers are your friends!



I haven't read such a uniquely comprehensive, yet simplified, article on Function Pointers before. Begins with a simple and understandable example, and concludes perfectly with the super-useful code snippets!
Great read, as always!