Introduction to using function pointers in C (or C++)

[Page updated: 2008-11-08 (hesa)]

Why function pointers anyway?

In C (C++) you can use function pointers to implement plugins or to change, at one place, the function to call, no matter where you use the function (through the pointer), or to remove “expensive” if statements in tight loops.

But instead of spending too much energy on talking we’ll continue with an example. Throughout this introduction we’ll use a feedback functionality. Your program wants to give feedback to the user and instead of using a variable which we switch over to choose the right feedback implementation we are going to use function pointers. Depending on what environment the user is using we can use a gui feedback or console based feedback. Later on, in introduction to writing plugins, we’ll dive into more practical use of them pointers.

Let’s settle for a feedback function prototype (stripped down functionality, no variable sized argument list etc):

int default_feedback(char *str)

The function returns an int. The first argument is the string to print. Let’s add an implementation to the function:

int default_feedback(char *str)

{

return fprintf(stdout, “%s”, str);

}

Please note, we haven’t used function pointers yet.We can use the function by calling it like this:

default_feedback(”Ordinary call\n”);

So far so good. Let’s define our first function pointer. Let’s create a variable feedback_fun that stores the pointer to the function we want to call.

int (*feedback_fun)(char *str) ;

We can see that this looks a bit like the function above. We’ve just added some “(*” and an extra “)”. What the live above says is: the function pointed to by feedback_fun returns an int and takes char *str as argument. Piece of cake, isn’t it? We can now use the variable to store the address to a function we want to use.

Let’s store the address in our function pointer:

feedback_fun = default_feedback ;

and call the function through the function pointer

feedback_fun(”Called using function pointer call\n”);

Was that it? Yes, neat isn’t it? So if we turn this into a program, including a main function and some comments, we get this:

/*
* Copyright (c) 2008, Henrik Sandklef
*
*/

#include <stdio.h>

/*
* Global varible poiting to th feedback function choosen
*
*/
int (*feedback_fun)(char *str) ;

/*
* Name:         default_feedback
* Args:           str - string to print
* Description:  Prints a string to given file
*/
int
default_feedback(char *str)
{
return fprintf(”%s”, str);
}

int main(int argc, char **argv)
{

/* Set feedback_fun to point at default feedback function */
feedback_fun = default_feedback ;

/* Call the  default_feedback in the ordinary way */
default_feedback(”Ordinary call\n”);

/* Call the default_feedback through the feedback_fun variable */
feedback_fun(”Called using function pointer call\n”);

return 0;
}

31 Comments to Introduction to using function pointers in C (or C++)

e8johan
October 9, 2008

There are two interesting features that can be used with function pointer. The first one is that it is possible to break out an if-clause selecting what to do from a tight loop. Given the example above:

if( special_case )
feedback_fun = special_feedback;
else
feedback_fun = default_feedback;

for( /* tight loop over items */ )
feedback_fun( /* item pointer */ );

Given the code above, we can save quite a lot of evaluations (beware, though, today’s compilers are probably smart enough to do this).

The second feature is what C++ folks calls virtual methods, but an example of that would consume too much space to show here. :-P

hesa
October 9, 2008

i am planning to write a follow up tonight (sleep is a poor substitute for coffee) where I’ll show how to simplify the use of function pointers by using a simple typedef

… after we (the two of us) can dive into the C++ field :)

hesa
October 10, 2008

i did sleep instead…. ;)

hesa
November 8, 2008
jeremiah
November 19, 2008

Very cool, I would like to see a more “real world” example because this seems quite useful.

payday advance loan
December 23, 2008

I come to your site because it keeps me entertained and aware of new things.

visit now
December 23, 2008

I come to your site because it keeps me entertained and aware of new things.

win now
December 24, 2008

i really loved your site and found it to be very friendly and helpfull.

click
December 25, 2008

In Zeiten von massenhaft Websitenmüll im Internet eine sehr gut aufgebaute Website, nicht überdimensioniertes Design und sehr gut recher-schierte Hintergrundinformationen.

guide
December 25, 2008

I finally decided to give you a little feedback ! well you got it! i love your site !!! no , really, its good…

get minted poker
December 25, 2008

This is a great page. And the contents are really that worth reading. I will add this to my own library

click
December 26, 2008

Howdy! Great site. Great content. Great! I can recommend this site to others!

bingo play for fun nodownload
December 27, 2008

I used this site to get information for that i had in my class. This is an excellent site for this information :)

tip
December 28, 2008

This site is truly a great resource thanks for all your hard work

reviews
December 29, 2008

Wow, this is a great web site. I am so glad I found it, thank you. It is funny, I was just talking to my friend about their web site, and they said they like your site too!

reviews
December 29, 2008

You have a great website. Keep up the good work.

no deposit online casino
December 29, 2008

Man, what a well set-up website!

boost credit score
December 31, 2008

Could you please send to me the contacts of developer of your site? It looks so damn good!

equifax information services
December 31, 2008

quite enjoyed your work .

directory
December 31, 2008

a really great homepage! i’m a big fan of your stuff although i’m just 16!

casin craps online
January 1, 2009

Lovely, informative site, thanks

visit
January 2, 2009

My god u kept me entertained.

visit
January 3, 2009

I’d just like to thank you for taking the time to create this internet website. It has been extremely helpful

win now
January 3, 2009

Hi! very amused by the website .

internet casino gambling online
January 4, 2009

I happened upon this site while following the links from another site. Your site is wonderful and i bookmarked it. Thank your for the hard work you must have put in to create this wonderful facility. Keep up the excellent work

tip
January 4, 2009

Super site darlings. Thanks awfully

visit now
January 4, 2009

Hi there, I must say that you have done a wonderful job on your site and I thoroughly enjoyed my stay here, I thank you for sharing it with me…

silversands casino
January 5, 2009

Thank you for the great web site - a true resource, and one many people clearly enjoy

jackpot slot
January 6, 2009

This nice is very good, i will recomend it to my friends and partners

click
January 6, 2009

Thanks for a lovely site, I am very impressed :-)

jeu de casino internet
January 6, 2009

Respekt! Ein wirlich gelungene Seite.

Leave a comment

Me elsewhere ..


Warning: Attempt to assign property of non-object in /www/hesa/wordpress/wp-includes/rss.php on line 440

Search

Categories