C Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesC Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old November 9th, 2012, 12:37 AM
shilpac shilpac is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Posts: 30 shilpac User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 h 3 m 34 sec
Reputation Power: 1
Function pointer

Can anyone explain why do we need function pointers ? Where it is used ?

Reply With Quote
  #2  
Old November 9th, 2012, 12:48 AM
dwise1_aol's Avatar
dwise1_aol dwise1_aol is offline
Contributing User
Dev Shed God 2nd Plane (6000 - 6499 posts)
 
Join Date: Jan 2003
Location: USA
Posts: 6,122 dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level)dwise1_aol User rank is General 14th Grade (Above 100000 Reputation Level) 
Time spent in forums: 2 Months 2 Weeks 3 Days 13 h 38 m
Reputation Power: 1949
Jump tables.

Passing to a function the function that it will need to call, selectable at run-time.

Passing to a CreateThread call the function that the thread will execute.

Just off the top of my head.

Reply With Quote
  #3  
Old November 9th, 2012, 12:50 AM
salem's Avatar
salem salem is online now
Contributed User
Click here for more information
 
Join Date: Jun 2005
Posts: 3,831 salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)salem User rank is General 12nd Grade (Above 100000 Reputation Level)  Folding Points: 153 Folding Title: Novice Folder
Time spent in forums: 2 Months 3 Weeks 2 Days 13 h 2 m 24 sec
Reputation Power: 1774
The standard library function qsort uses function pointers
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

Reply With Quote
  #4  
Old November 9th, 2012, 12:56 AM
clifford's Avatar
clifford clifford is offline
Contributing User
Dev Shed Demi-God (4500 - 4999 posts)
 
Join Date: Aug 2003
Location: UK
Posts: 4,804 clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level) 
Time spent in forums: 1 Month 2 Days 16 h 42 m 47 sec
Reputation Power: 1800
It is the address of a function through which the function can be called. Since it is a variable, the call can be dynamically determined at runtime rather than fixed when the code is built.

One use is in callbacks where you can for example pass a pointer to a function to some library code so that that library can call your code without prior knowledge of its existence. This is how the standard library qsort() function works for example to allow it to sort any type of object using user defined ordering rules.

There was once an excellent web site www.function-pointers.org which provided more that you would ever need to know about the subject, but it appears to be down or extinct. A reasonable summary of the subject can be found here
Comments on this post
shilpac agrees!

Reply With Quote
  #5  
Old November 9th, 2012, 01:24 AM
serafon serafon is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 13 serafon User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 1 m 44 sec
Reputation Power: 0
Quote:
Originally Posted by shilpac
Can anyone explain why do we need function pointers ? Where it is used ?

Function pointers add C++ like properties to C. You can create class like behaviour using structs and function pointers... Function pointers allows you to use functions like a variable and since functions have power to do something organization of complex programs can be more easier and flexible. You can create more generic behaviours and abstraction can be achieved. void pointers are also used frequently with function pointers.

Reply With Quote
  #6  
Old November 9th, 2012, 01:52 AM
shilpac shilpac is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Oct 2012
Posts: 30 shilpac User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 h 3 m 34 sec
Reputation Power: 1
Thanks guys.

Reply With Quote
  #7  
Old November 9th, 2012, 06:01 AM
clifford's Avatar
clifford clifford is offline
Contributing User
Dev Shed Demi-God (4500 - 4999 posts)
 
Join Date: Aug 2003
Location: UK
Posts: 4,804 clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level) 
Time spent in forums: 1 Month 2 Days 16 h 42 m 47 sec
Reputation Power: 1800
Quote:
Originally Posted by serafon
Function pointers add C++ like properties to C.

That is a bit misleading - C has always supported function pointers, long before C++ even existed - nothing has been "added". In fact it is the other way around, C++ uses function pointers to enable some of its features such as virtual functions. But if that is what you are trying to achieve - just use C++!

Reply With Quote
  #8  
Old November 9th, 2012, 07:52 PM
c99tutorial c99tutorial is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 8 c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 2 h 6 m 33 sec
Reputation Power: 0
A function pointer can be used to make your code more "flexible" and ultimately easier to use.

Suppose you want a function called get_data which prompts the user for some number, and then validates that number based on some rule which is context-dependent. In this case, we can define some simple validator functions and then give the name of the function to our get_data function.

C Code:
Original - C Code
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. // get_data(data, prompt, validator): Read data from user and use a custom validator.
  5. // The data is verified by calling the specified validator. If the validator returns false,
  6. // then the prompt is repeated until the user enters valid data.
  7. void get_data(double *data, const char *prompt, bool (*validator)(double));
  8.  
  9. // Validator functions: these should return true if the value is valid; false otherwise.
  10. bool validate_height(double height);
  11. bool validate_weight(double weight);
  12. bool validate_any(double any) {return true;}  // always valid
  13.  
  14. // main: demonstrate use of get_data() with function pointers
  15. int main()
  16. {
  17.     double height, weight, random;
  18.     get_data(&height, "Enter your height in cm: ", validate_height);
  19.     get_data(&weight, "Enter your weight in kg: ", validate_weight);
  20.     get_data(&random, "Enter a random number: ", validate_any);
  21.    
  22.     printf("\nThanks, here is your info summary:\n"
  23.             "Height: %.2f cm\n"
  24.             "Weight: %.2f kg\n"
  25.             "Random: %g\n",
  26.             height, weight, random);
  27.     return 0;
  28. }
  29.  
  30. bool validate_height(double height)
  31. {
  32.     if (height < 5.0 || height > 300.0)
  33.         return false;
  34.     return true;
  35. }
  36.  
  37. bool validate_weight(double weight)
  38. {
  39.     if (weight < 10.0 || weight > 500.0)
  40.         return false;
  41.     return true;
  42. }
  43.  
  44. void get_data(double *data, const char *prompt, bool (*validator)(double))
  45. {
  46.     for (;;) {
  47.         printf("%s", prompt);
  48.         if (scanf("%lf", data) != 1) {
  49.             fflush(stdin)// skip over non-numeric data
  50.             printf("A number is required.\n");
  51.             continue;
  52.         }
  53.         getchar()// skip whitespace
  54.         if ((*validator)(*data))
  55.             return;
  56.         printf("Sorry, that was not a valid number.\n");
  57.     }
  58. }


Using such a scheme is nice, because if we add more rules later, we don't need to change get_data to handle them. We just define another function and pass it along. The get_data function does "the right thing" as long as the validator is properly defined.

Reply With Quote
  #9  
Old November 9th, 2012, 08:57 PM
EEmaestro EEmaestro is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Apr 2012
Posts: 58 EEmaestro User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 Day 17 h 52 m 2 sec
Reputation Power: 2
What if the function takes arguments? Then is it still possible to select the function by dereferencing a pointer to the function that changes at run time? I think not.

Reply With Quote
  #10  
Old November 9th, 2012, 10:43 PM
serafon serafon is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 13 serafon User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 1 m 44 sec
Reputation Power: 0
Quote:
Originally Posted by EEmaestro
What if the function takes arguments? Then is it still possible to select the function by dereferencing a pointer to the function that changes at run time? I think not.


Function already has parameters if you look carefully. There is no difference from an ordinary function, it has all the capabilities.

One problem here is, (actually not a problem but getting more flexibility) using functions with different number of arguments. Because there is no restriction about arguments of the function that the pointer points to but the number and type should be always same.

One solution is to use va_arg, va_list etc (i also asked in another topic) and second may be an argument which is a void pointer and points to a structure of arguments.

Reply With Quote
  #11  
Old November 10th, 2012, 03:05 AM
clifford's Avatar
clifford clifford is offline
Contributing User
Dev Shed Demi-God (4500 - 4999 posts)
 
Join Date: Aug 2003
Location: UK
Posts: 4,804 clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level)clifford User rank is General 12nd Grade (Above 100000 Reputation Level) 
Time spent in forums: 1 Month 2 Days 16 h 42 m 47 sec
Reputation Power: 1800
Quote:
Originally Posted by EEmaestro
What if the function takes arguments? Then is it still possible to select the function by dereferencing a pointer to the function that changes at run time? I think not.


That can be done without any problem; did you look at any of the links already posted? The function passed to qsort() for example takes two arguments.

For example:

Code:
double(*trig_fn)(double);
trig_fn = &sin ;
double x = trig_fn( theta ) ;


Note that explicit de-referencing is not required, though allowed.

In the function pointer declaration, the return value and the parameter types form part of the function-pointer type. At compile time at least, the data type is checked for consistency. You can also have a generic function pointer type and cast it to another in order to force a call for which the parameter types are not a match - obviously you'd do that with care, but it is sometimes useful - for example you might have a call back that does not need any parameters being called from a library that provides parameters. In this case you could have a dummy parameter and ignore it or cast the pointer to the accepted type.

In C the stack frame setup-up and tear down code is performed by the caller not the called function, so nothing bad happens in terms of stack management, but interpreting arguments that were not explicitly passed will only yield junk, modifying such parameters or dereferencing pointer arguments will likely cause memory corruption and even more trouble.

Reply With Quote
  #12  
Old November 10th, 2012, 03:15 AM
c99tutorial c99tutorial is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 8 c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level)c99tutorial User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 2 h 6 m 33 sec
Reputation Power: 0
Quote:
Originally Posted by clifford
Note that explicit de-referencing is not required, though allowed.


Indeed. The above example can also be written (more clearly in my opinion):

C Code:
Original - C Code
  1.     double (*trig_fn)(double);
  2.     trig_fn = sin ;
  3.     double x = (*trig_fn)(theta);


This is the style used by the K&R book to explain function pointers. The unadorned sin should already be an address, and the identifier (*trig_fn)(...) has the type `double', wheras the unadorned trig_fn has type `double (*)(double)'

Reply With Quote
  #13  
Old November 10th, 2012, 09:15 AM
serafon serafon is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 13 serafon User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 1 m 44 sec
Reputation Power: 0
Quote:
Originally Posted by clifford
In C the stack frame setup-up and tear down code is performed by the caller not the called function, so nothing bad happens in terms of stack management, but interpreting arguments that were not explicitly passed will only yield junk, modifying such parameters or dereferencing pointer arguments will likely cause memory corruption and even more trouble.


Can you explain this more please? Do you say it is not a good idea to pass in a void pointer to a function that points to a parameter list and dereference it in the called function?

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesC Programming > Function pointer

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap