Home > OOP344 > Pointers to functions in C/C++ intro

Pointers to functions in C/C++ intro

Pointers to functions are a very interesting and elegant programming technique. They can be used to replace long switch or if statements!

Anyone can start using pointers to functions all you have to do is to understand what they are and to learn its syntax.

What is a Function Pointer?

Function pointers are simply pointers that point to a function! Functions have addresses in memory just as variables do.

Syntax

The syntax can be a little strange if you are seeing for the first time but its very easy to grasp.

Suppose we have the following function


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

we can start creating a pointers to function by writing

int (*fptr)(int, int);

int is the return type of the function and (int, int) is the arguments the function accepts.

The next step is to give our pointer to function the function’s address. We do that with the following code

fptr = add;

Now that fptr points to the “add” function we can actually start calling out function using the fptr pointer. We use the code below to do it.


int c = 0;
c = (*fptr)(a, b);

As you can see pointers functions are easy to learn 🙂 I will make more posts soon to show how you can get rid of a long switch statement by using pointers to functions. I have also posted a compilable example below so you can experiment with.


/* Author: Fardad Soleimanloo */
#include
int add(int a, int b){
return a+b;
}
int main(){
int (*fptr)(int, int);
int a = 10;
int b = 20;
int c;
fptr = add;
c = (*fptr)(a, b);
printf("%d\n", c);
return 0;
}

Categories: OOP344
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: