Function Pointer

Table of Contents
1.What are function pointers?
2.What advantages does this give me?
3.Example – Iterating through a list
-Example 1 – Code
-Example 2 – Code
-Example 3 – Code
4.Some useful tips for programmers
-Short hand notation
-Module abstraction and indepenence

What are function pointers?

Function pointers are means to add another level of indirection. Remember pointers to variables? Function pointers are no different.

Let’s say that there are two identical functions a and b (by identical we mean that the functions have the same return type and the same parameter type). We also declare a function pointer p. The function pointer is defined such that it shares the same return type and parameter types as a and b. By assigning the address of a to p, p = a;, calls to p will in effect yield calls to a. Likewise, p can be assigned b, where calls to p yield calls to b. Getting dizzy yet?

Here’s a very simple example which works with C and C++.

#include &ltstdio.h>

void a(void)
{
printf(“a was called.\n”);
}

void b(void)
{
printf(“b was called.\n”);
}

int main(void)
{
void (*p)(void); /* This is a function pointer declaration */

p = a;
(*p)(); /* Using function pointer p */
p = b;
(*p)(); /* Using function pointer p (again) */
return 0; /* Standard exit procedure in UNIX */
}

As you can see, the function pointer declaration looks somewhat complicated. The “standard remedy” for this is to create a new function pointer type by using the typedef operator.

Same example again using the typedef operator.

#include &ltstdio.h>

typedef void (*FuncType)(void); /* FuncType is a function pointer type */

void a(void)
{
printf(“a was called.\n”);
}

void b(void)
{
printf(“b was called.\n”);
}

int main(void)
{
FuncType p; /* This is a function pointer declaration */

p = a;
(*p)(); /* Using function pointer p */
p = b;
(*p)(); /* Using function pointer p (again) */
return 0; /* Standard exit procedure in UNIX */
}

What advantage does this give me?

As you probably learned in your first programming courses, pointers to variables allows you to modify variable contents from a non-local environment. This gives the flexibility of writing generic functions which do not alter “known” global variables, but references to “unknown” variables. Such functions can be reused. Function pointers gives you the same flexibility, but at a higher level. Instead of calling a “known” function, one can call any arbitrary “unknown” function. This is the main advantage of function pointers: greater flexibility and better code reuse.

Example – Iterating through a list

In this example I’ll show a very common (and naive) solution for iterating through a list, then a somewhat “better” solution and last I’ll show a general and resuable solution.

The list is a list of strings and we want to iterate it for printing to screen. As a twist, we also want to print out the a list of the string lengths rather than the strings.

Example 1 – Code:
This is a very naive implementation.

#include &ltstdio.h>

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;
ListRecord* i;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

printf(“List begins\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text: %s\n”, i->text);
printf(“List ends\n”);

printf(“List begins (lengths)\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text Length: %d\n”, strlen(i->text));
printf(“List ends\n”);

return 0;
}

Example 2 – Code:
This is a better implementation. Functionality has been moved out into separate functions. printList and printListStrLen are new functions.

#include &ltstdio.h>

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

void printList(List* list)
{
ListRecord* i;

printf(“List begins\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text: %s\n”, i->text);
printf(“List ends\n”);
}

void printListStrLen(List* list)
{
ListRecord* i;

printf(“List begins (reversed)\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text Length: %s\n”, strlen(i->text));
printf(“List ends\n”);
}

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

printList(list);
printListStrLen(list);

return 0;
}

Example 3 – Code:
This solution is the best of the three since it allows for high code reuse. It makes use of function pointers for performing the actual printing and it separates the “for-looping” into a function of its own. The three new key features in this example is ListRecordOperation, print, printStrLen and listForEach. Note that adding new features such as printing the text in reverse is now very easy. Just add a function that is compatible with the ListRecordOperation type and call listForEach with the function as argument. No more tedious moments of writing for-loops and such, now you can focus on the problem at hand instead.

#include &ltstdio.h>

typedef void (*ListRecordOperation)(const char*);

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

/* function compatible with ListRecordOperation */
void print(const char* text)
{
printf(“Text: %s\n”, text);
}

/* function compatible with ListRecordOperation */
void printStrLen(const char* text)
{
printf(“Text Length: %s\n”, strlen(text));
}

void listForEach(List* list, ListRecordOperation op)
{
ListRecord* i;

for(i = list; i != NULL; i = i->next)
(*op)(list->text); /* Calling whatever op points to with i->text
as argument */
}

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

listForEach(list, print);
listForEach(list, printStrLen);

return 0;
}

Useful tips for programmers
Short hand notation
Function pointers may be used with a shorthand notation. Instead of dereferencing the function pointer with an asterisk:

p = a;
(*p)();

you can use it like this:

p = a;
p();

as if it was an “ordinary” function. Gives C an aesthetic appeal.

Function Pointers

0 comments Table of Contents
1.What are function pointers?
2.What advantages does this give me?
3.Example – Iterating through a list
-Example 1 – Code
-Example 2 – Code
-Example 3 – Code
4.Some useful tips for programmers
-Short hand notation
-Module abstraction and indepenence

What are function pointers?

Function pointers are means to add another level of indirection. Remember pointers to variables? Function pointers are no different.

Let’s say that there are two identical functions a and b (by identical we mean that the functions have the same return type and the same parameter type). We also declare a function pointer p. The function pointer is defined such that it shares the same return type and parameter types as a and b. By assigning the address of a to p, p = a;, calls to p will in effect yield calls to a. Likewise, p can be assigned b, where calls to p yield calls to b. Getting dizzy yet? 😉

Here’s a very simple example which works with C and C++.

#include &ltstdio.h>

void a(void)
{
printf(“a was called.\n”);
}

void b(void)
{
printf(“b was called.\n”);
}

int main(void)
{
void (*p)(void); /* This is a function pointer declaration */

p = a;
(*p)(); /* Using function pointer p */
p = b;
(*p)(); /* Using function pointer p (again) */
return 0; /* Standard exit procedure in UNIX */
}

As you can see, the function pointer declaration looks somewhat complicated. The “standard remedy” for this is to create a new function pointer type by using the typedef operator.

Same example again using the typedef operator.

#include &ltstdio.h>

typedef void (*FuncType)(void); /* FuncType is a function pointer type */

void a(void)
{
printf(“a was called.\n”);
}

void b(void)
{
printf(“b was called.\n”);
}

int main(void)
{
FuncType p; /* This is a function pointer declaration */

p = a;
(*p)(); /* Using function pointer p */
p = b;
(*p)(); /* Using function pointer p (again) */
return 0; /* Standard exit procedure in UNIX */
}

What advantage does this give me?

As you probably learned in your first programming courses, pointers to variables allows you to modify variable contents from a non-local environment. This gives the flexibility of writing generic functions which do not alter “known” global variables, but references to “unknown” variables. Such functions can be reused. Function pointers gives you the same flexibility, but at a higher level. Instead of calling a “known” function, one can call any arbitrary “unknown” function. This is the main advantage of function pointers: greater flexibility and better code reuse.

Example – Iterating through a list

In this example I’ll show a very common (and naive) solution for iterating through a list, then a somewhat “better” solution and last I’ll show a general and resuable solution.

The list is a list of strings and we want to iterate it for printing to screen. As a twist, we also want to print out the a list of the string lengths rather than the strings.

Example 1 – Code:
This is a very naive implementation.

#include &ltstdio.h>

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;
ListRecord* i;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

printf(“List begins\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text: %s\n”, i->text);
printf(“List ends\n”);

printf(“List begins (lengths)\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text Length: %d\n”, strlen(i->text));
printf(“List ends\n”);

return 0;
}

Example 2 – Code:
This is a better implementation. Functionality has been moved out into separate functions. printList and printListStrLen are new functions.

#include &ltstdio.h>

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

void printList(List* list)
{
ListRecord* i;

printf(“List begins\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text: %s\n”, i->text);
printf(“List ends\n”);
}

void printListStrLen(List* list)
{
ListRecord* i;

printf(“List begins (reversed)\n”);
for(i = list; i != NULL; i = i->next)
printf(“Text Length: %s\n”, strlen(i->text));
printf(“List ends\n”);
}

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

printList(list);
printListStrLen(list);

return 0;
}

Example 3 – Code:
This solution is the best of the three since it allows for high code reuse. It makes use of function pointers for performing the actual printing and it separates the “for-looping” into a function of its own. The three new key features in this example is ListRecordOperation, print, printStrLen and listForEach. Note that adding new features such as printing the text in reverse is now very easy. Just add a function that is compatible with the ListRecordOperation type and call listForEach with the function as argument. No more tedious moments of writing for-loops and such, now you can focus on the problem at hand instead.

#include &ltstdio.h>

typedef void (*ListRecordOperation)(const char*);

typedef struct ListRecord List;

struct ListRecord {
char* text;
List* next;
};

/* function compatible with ListRecordOperation */
void print(const char* text)
{
printf(“Text: %s\n”, text);
}

/* function compatible with ListRecordOperation */
void printStrLen(const char* text)
{
printf(“Text Length: %s\n”, strlen(text));
}

void listForEach(List* list, ListRecordOperation op)
{
ListRecord* i;

for(i = list; i != NULL; i = i->next)
(*op)(list->text); /* Calling whatever op points to with i->text
as argument */
}

List* listInsert(List* list, const char* text)
{
ListRecord* rec;

rec = (ListRecord*)malloc(sizeof(ListRecord));
rec->text = strdup(text); /* Make a copy of string */
rec->next = list; /* Link in old list */
return list;
}

int main(void)
{
List* list;

list = NULL;
list = listInsert(list, “World!”);
list = listInsert(list, “Hello”);

listForEach(list, print);
listForEach(list, printStrLen);

return 0;
}

Useful tips for programmers
Short hand notation
Function pointers may be used with a shorthand notation. Instead of dereferencing the function pointer with an asterisk:

p = a;
(*p)();

you can use it like this:

p = a;
p();

as if it was an “ordinary” function. Gives C an aesthetic appeal. 😉

  1. Can I just say what a relief to discover someone who actually knows what theyre talking about on a internet. You really know how to bring an issue to light and make it important. Far more people have to read this and realize this side on the story. I cant consider youre not more well-known since you really have the gift.

  2. Hi buddy, your blog’s design is easy and clean and i like it. Your blog articles are superb. Please preserve them coming. Greets!!!

  3. I’ve been browsing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. Personally, if all website owners and bloggers made good content as you did, the internet will be a lot more useful than ever before.

  4. Excellent post. I was checking constantly this blog and I am impressed! Extremely helpful info specifically the last part 🙂 I care for such information a lot. I was seeking this certain information for a long time. Thank you and good luck.

  5. I have been surfing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. Personally, if all site owners and bloggers made good content as you did, the web will be much more useful than ever before.

  6. Hello there, just became aware of your blog through Google, and found that it’s truly informative. I’m gonna watch out for brussels. I’ll be grateful if you continue this in future. Numerous people will be benefited from your writing. Cheers!

  7. hi, solid web log, just I don’t see how to add your site in my rss reader. Could are Assist me please?

  8. We still cannot quite believe I could often be one of those reading through the important suggestions found on your website. My family and I are sincerely thankful on your generosity and for providing me the chance to pursue my own chosen career path. Thanks for the important information I acquired from your website.

  9. hey there and thank you for your information – I have certainly picked up something new from right here. I did however expertise a few technical issues using this site, since I experienced to reload the website a lot of times previous to I could get it to load correctly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if ads and marketing with Adwords. Well I’m adding this RSS to my email and can look out for a lot more of your respective exciting content. Make sure you update this again very soon..

  10. I do enjoy the manner in which you have presented this particular challenge and it really does present me personally some fodder for thought. However, coming from what I have personally seen, I simply just wish as the remarks stack on that individuals keep on point and don’t start upon a soap box involving some other news of the day. All the same, thank you for this excellent point and though I can not concur with the idea in totality, I regard your point of view.

  11. I do like the manner in which you have presented this issue plus it does provide me some fodder for consideration. Nonetheless, coming from what I have observed, I just trust when the reviews pack on that individuals remain on issue and in no way start upon a soap box associated with some other news du jour. Yet, thank you for this exceptional piece and even though I do not really agree with this in totality, I regard the perspective.

  12. My partner and I stumbled over here coming from a different website and thought I may as well check things out. I like what I see so now i am following you. Look forward to exploring your web page for a second time.

  13. The man who has nothing to do is always the busiest.

  14. Have you ever considered publishing an ebook or guest authoring on other sites? I have a blog based upon on the same subjects you discuss and would really like to have you share some stories/information. I know my readers would enjoy your work. If you are even remotely interested, feel free to send me an email.

  15. Whats up, That is a good summation, I located your blog checking google for any similar subject and discovered this. I couldnt discover as well much other tips and facts on this posting, so it was excellent to discover this one. I will probably be returning to consider a number of other articles that you simply have written one more time.

  16. Wow, awesome blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is wonderful, as well as the content!

  17. I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all web owners and bloggers made good content as you did, the internet will be a lot more useful than ever before.

  18. I stumbled upon this article from twitter and shall look for upates in the future.

  19. I am going to post additional thoughts after I evaluate the particulars within this page.

  20. Hi there are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding knowledge to make your own blog? Any help would be greatly appreciated!

  21. I uncovered this information by way of twitter and will check for upates in the future.

  22. Well written and really useful. I’m thankful you took the time to post this because it was extremely helpful.

  23. Just wanted to say that this blog is kind of like another one that I found a few days ago but for the life of me cannot remember. Does anyone know which blog I am talking about?

  24. Sensational info. I look forward to seeing more.

  25. Hey I found this website to be really interesting! Bookmarked! http://extremesports.newsbabble.info/page/18

  26. This really solved my problem, thank you!

  27. Hey I discovered this website to be actually interesting! Bookmarked! http://newsbabble.info/verizoniphone661.html

  28. Just like someone else documented what a wonderful blog this is. Normally I dont take the time with a comment however for your energy and efforts you are entitled to 1. Effectively said

  29. Thanks for the excellent details, It was exactly what I was searching for, and really useful.

  30. You actually covered a few curious points in this posting. I came across this article by using Google and I have to confess that I am now subscribed for your website, it is quite great 😀

  31. Hey I absolutely enjoy this article and it has been so admirable and I am gonna tweet it. I Have to say the exceptional analysis this article has is definetly exceptional !! No one does that additional research these days? Hats off to You 🙂 Just another tip you definetlyintroduce some Translator Application for your Worldwide Readers .

  32. Hi I definetly adore your write-up and it is too agreeable and I am surely going to tweet it. I Have to say the exceptional analysis you have done is trully extraordinary ! No one does that additional research now days? Bravo !! Also another advise to you is that you shouldset up any Translator Application for your Worldwide Audience !!!

  33. Really good post! I’m just starting out in community marketing media and trying to learn how to do it well – information like this blog are incredibly helpful. As our company is based in the Virgin Islands, it’s all a bit new to us. The example above is something that I worry about as well, how to show your own genuine excitement and share the fact that your product is helpful in that case

  34. Nice Blog! Please let your readers know that I found an awesome site they would enjoy too – http://aboutandroid.com – Everything about android! Android just started outselling the iphone too!

  35. I’m not sure where you’re getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for great info I was looking for this info for my mission.

  36. Most I can state is, I’m not sure what to really say! Except naturally, for the great tips which are shared on this blog. I’ll think of a zillion fun methods to read the content articles on this site. I think I will eventually make a move employing your tips on areas I could not have been able to address alone. You are so clever to let me be one of those to profit from your practical information. Please recognize how considerably I enjoy the whole thing.

  37. I regard something really interesting about your blog so I saved to favorites .

  38. Wow! This can be one particular of the most beneficial blogs We’ve ever arrive across on this subject. Basically Wonderful. I am also an expert in this topic therefore I can understand your hard work.

  39. I simply want to mention I am just beginner to weblog and honestly loved you’re web page. Almost certainly I’m going to bookmark your blog . You surely have very good well written articles. Bless you for sharing your web site.

  40. Thank you for taking the effort and time to compose something that is invoking

  41. Hello.This post got motivating, especially since I was hunting for applying for grants this subject last Tuesday.

  42. Hey I definetly like your story and it is too pleasing hence I am going to tweet it. One thing to say the Indepth analysis this article has is greatly exceptional !! Who goes that extra mile now days? Well Done 🙂 Just another tip you shouldinstall a Translator Application for your Worldwide Users 🙂

  43. Hello I definetly dig this article and it was too pleasing so I am definetly going to save. One thing to say the Superb analysis you have done is trully exceptional !! No one goes that extra mile these days? Well Done . Also another advise to you is that you shouldset up a Translator Application for your Global Users !

  44. Dude thank you for such a good article. I do agree with you

  45. I must say your site is really helpful I also love the design, its amazing!. I don’t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds.

  46. Thank you for another excellent post. The place else may just anyone get that kind of info in such a perfect manner of writing? I’ve a presentation next week, and I’m at the look for such information.

  47. great blog but some pictures will make it better

  48. I am not able to view this website correctly on saffari I believe there’s a downside

  49. I’m not able to view this web site properly on firefox I feel there is a downside

  50. Can I put up your submit to my blog? I will add a inbound link to your forum. That’s one really sweet post.

  51. Pretty nice post. I simply stumbled upon your weblog and wanted to mention that I’ve truly enjoyed browsing your blog posts. After all I will be subscribing in your rss feed and I am hoping you write again soon!

  52. Hey! That’s a extremely nice post. I’m very positive I’ll suggest it to my co-workers.In the event you publish extra posts please e-mail them to me.

  53. It had been some time since I visited web site with such high quality information. Thansk loads for the helpful information

  54. I think other website proprietors should take this web site as an model – very clean and wonderful style and design, as well as the content. You are an expert in this topic!

  55. Nice post. I learn one thing more difficult on different blogs everyday. It is going to all the time be stimulating to read content from different writers and apply a bit of one thing from their store. I’d prefer to use some with the content on my blog whether or not you don’t mind. Natually I’ll offer you a link in your web blog. Thanks for sharing.

  56. Neat blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple tweeks would really make my blog stand out. Please let me know where you got your design. Kudos

  57. Cherished will most likely be a really significant incidents that you experienced. You are going to surely should make it charming as you possibly can. Via costume to all your take into account for your specific red wine for top level man’s melted, factor ought operating in just the thing framework.

  1. February 20th, 2011
    Trackback from : Yankee Candles Cheap

Leave a reply to Heidy Mawhinney Cancel reply