473,597 Members | 2,820 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Function pointer Advantage

Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?

Thanks and regards
Rajesh
Nov 13 '05 #1
11 15764
On Wed, 29 Oct 2003 22:29:50 -0800, Rajesh wrote:
Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?


You couldn't make a generic function like this without function pointers.
qsort can sort any array as long as you can give it a function to compare
two elements.
/* base : array of stuff
nmemb : amount of stuff
size : size of a stuff
compar : function to compare to stuffs */
void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(co nst void *, const void *));
--
NPV

"the large print giveth, and the small print taketh away"
Tom Waits - Step right up

Nov 13 '05 #2
ra****@tridenti nfosol.com (Rajesh) wrote in message news:<b2******* *************** ***@posting.goo gle.com>...
Please let me know the advantage of function pointer?
useful for expressing certain designs
Is it fast calling function using function pointer?
no. Likely slightly slower than a direct call
Is it possible to use function pointer to optimise code?


optimise it for what?

Function poiters could save space if used to implement a simple interpretor.
Think array of pointers to functions.

--
Nick Keighley
Nov 13 '05 #3
ra****@tridenti nfosol.com (Rajesh) wrote in message news:<b2******* *************** ***@posting.goo gle.com>...
Dear All,

Please let me know the advantage of function pointer?
Function pointers allow you to pass functions as parameters to other
functions (read up on qsort and bsearch), implement function lookup
tables (e.g., call a function based on a name or other criteria), etc.
Example:

/*
** h is a pointer to a function taking one int parameter and returning
int
*/
int foo (int x, int (*h)(int))
{
return h(x);
}

int bar (int x)
{
return x * 2;
}

int main (void)
{
int y = foo (2, bar);
return 0;
}
Is it fast calling function using function pointer?
No faster than calling the function directly.
Is it possible to use function pointer to optimise code?
Depends on what you mean by "optimize". Probably not.

Thanks and regards
Rajesh

Nov 13 '05 #4


Rajesh wrote:
Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?


I wouldn't label the use of function pointers in terms of
optimization or fast calls. Instead I style my understanding
of function pointers in the terms of pointer variables. In C a function,
by itself, is not a variable. Pointers to functions are variables and
can be used in assignments, arrays, passed to functions, etc.

Examples:

/* type definition of a function pointer */
typedef int (*FuncPointer)( void);

/* A function definition */
int foo(void)
{
return 6;
};

int bar(void)
{
return 10;
};

You cannot do this:
foo = bar; /* ERROR */

But you can do this:
FuncPointer p1,p2;
/* assignments */
p1 = foo;
p2 = bar;
p1 = p2;

/* array of function pointers */
FuncPointer parray[] = {foo,bar};
int d = parray[0]();

/* As a function parameter */
int Afunction(int i, FuncPointer p){return i*p();};
and the call:
int d = Afunction(2,foo );

/************ Code Example *************** ******/
#include <stdio.h>

typedef int (*FuncPointer)( void);

/* A function definition */
int foo(void)
{
return 6;
};

int bar(void)
{
return 10;
};

int Afunction(int i, FuncPointer p){return i*p();};

int main(void)
{
FuncPointer p1,p2;
FuncPointer parray[] = {foo,bar};
int d;

/* assignments */
p1 = foo;
p2 = bar;
printf("p2 returns %d\n",p2());

/* array of function pointers */
d = parray[0]();
printf("d = %d\n",d);

/* As a function parameter */
d = Afunction(2,foo );
printf("d = %d\n",d);
return 0;
}
/*************** ********END**** ***********/

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #5

"Rajesh" <ra****@trident infosol.com> wrote in message
news:b2******** *************** **@posting.goog le.com...
Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?


These are homework questions aren't they?

There are many uses for function pointers. For example, in my library LTM I
use them in the modular exponentiation to save "if" statements. That is
three diff reduction algorithms have the same prototype and can be used [one
at a time] by the function. So I make a pointer to the function and use
that instead of doing if's everywhere I need to call it.

e.g. instead of

if (doing_my_homew ork == 1) {
a(some_data);
} else if (doing_my_homew ork == 2) {
b(some_data);
} else {
/// etc
}

I do one case of
if (blah) {
func = a;
} else if (bleh) {
func = b;
} else {
/// etc
}

then I just call func(some_data) everywhere I needed one of them.

Tom
Nov 13 '05 #6
Rajesh wrote:

Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?


The principal advantage of a function pointer is that
it allows you to select the called function at run time
instead of at compile time.

("Huh?")

Example:

int function(void) {...} /* an actual function */
int junction(void) {...} /* another function */
int (*fptr)(void); /* a function pointer */
...
x = function(); /* always calls `function' */
y = junction(); /* always calls `junction' */
z = (*fptr)(); /* calls ... what? */

The final line (which could also be written `z = fptr();',
by the way) calls a function, but just which function it calls
depends on the value stored in `fptr'. If you execute that
line several different times with several different `fptr'
settings, the exact same line of code can call a different
function each time.

It's really not that different from using data pointers:

int x; /* a variable */
int y; /* another */
int *p; /* a pointer */
...
x = 42; /* always stores to `x' */
y = 624; /* always stores to `y' */
*p = 666; /* stores to ... where? */

Depending on the value in `p', the final line might store
to `x' or to `y' or to somewhere else entirely, and the
destination might be different at each execution. You get to
choose the destination at run time instead of fixing it
immutably at compile time -- that's the advantage of a data
pointer, and the advantage of a function pointer is similar.

--
Er*********@sun .com
Nov 13 '05 #7
Rajesh wrote:

Dear All,

Please let me know the advantage of function pointer?
Is it fast calling function using function pointer?
Is it possible to use function pointer to optimise code?

Thanks and regards
Rajesh


Hi Rajesh

Imagine, you're a library writer.

The library is delivered, but the user/developer wants to change some
aspects, like 'what to do with errors/warnings'?

a great way is to let him choose his own functions:

(libxml2):
ctxt->vctxt.error = (xmlValidityErr orFunc) dummy;
ctxt->vctxt.warnin g = (xmlValidityWar ningFunc) dummy;
(ctxt is a pointer to a structure, containing a structure with some
function pointers, which might be by default fprintf),
now he can write the messages to a logfile, f.e.

or you have some functions, but there's a way to augment them:
(openssl2):
SSL_CTX_set_ver ify(ctx, SSL_VERIFY_PEER , verify_callback );
(a function pointer:) ~~~~~~~~~~~~~~~

Ok, this certificate verification error is not fatal after all...

or, all the functions are your's, but there's a choice of algorithm:

if (!(si = PKCS7_add_signa ture(p7, signcert, pkey, EVP_md5())))
/* (who needs lisp?)))) */

now it's md5 and not sha1

there's more, but those are some ideas.

Wolfgang
Nov 13 '05 #8
"John Bode" <jo*******@my-deja.com> wrote in message
news:43******** *************** ***@posting.goo gle.com...
ra****@tridenti nfosol.com (Rajesh) wrote in message

news:<b2******* *************** ***@posting.goo gle.com>...
....
Is it fast calling function using function pointer?

No faster than calling the function directly.


That is probably true.
Is it possible to use function pointer to optimise code?

Depends on what you mean by "optimize". Probably not.


Using function pointers /may/ improve code maintainability . If that counts
as "optimisati on" depends on the OP.

My favourite example is when the control flow looks something like this:

input
|
v
+---------------+
| shared code 1 |
+---------------+
/ | \
/ | \
v v v
+--------------------+
| different code |
| depending on input |
+--------------------+
\ | /
\ | /
vvv
+---------------+
| shared code 2 |
+---------------+

Of course, one can branch in the middle using a switch or an if ladder,
but taking a function pointer as part of 'input' is more readable, IMO.

It is also called a 'callback' :-)
Nov 13 '05 #9

"Peter Pichler" <pi*****@pobox. sk> wrote in message
Is it possible to use function pointer to optimise code?

Depends on what you mean by "optimize". Probably not.


Using function pointers /may/ improve code maintainability . If that
counts as "optimisati on" depends on the OP.

In programming "optimisati on" means making the program produce the same
output (or at least still acceptable output) in a shorter running time.

A function pointer is very unlikely to optimise code, since the function has
to be called indirectly, which implies a few extra machine operations to
load the pointer and do the jump.

Some compilers will also do cross-function optimisation, and using a
function pointer will prevent this.

However the overhead is generally small, so it is unlikely that you can
significantly speed up code by replacing a function pointer with a direct
call. You should use a function pointer wherever it makes code more
readable, more general, or reduces dependencies of one function on anther.
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
4977
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined signature. When developing this lib, I figured that the pointer-to-member-function, although seemingly an attractive solution, does not work well for us.
8
2952
by: Muthu | last post by:
I've read calling conventions to be the order(reverse or forward) in which the parameters are being read & understood by compilers. For ex. the following function. int Add(int p1, int p2, int p3); The parameters here can be read either in the forward order from p1 till p3 or reverse order from p3 till p1. Can anyone explain what is the advantage/disadvantage of either of
89
6445
by: Sweety | last post by:
hi, Is main function address is 657. its show in all compiler. try it & say why? bye,
3
2298
by: Dennis Chang | last post by:
Hi all, I was reading about function pointers and came across something which intrigued me. K&R2 calls qsort (pg.119) within main as so: qsort( (void **) lineptr, 0, nlines-1, (int (*) (void *, void*))(numeric ? numcmp : strcmp) ); I guess what interests me is the nameless function pointer and then the
1
6242
by: Mike | last post by:
In C, we can typedef pointer to functions, and therefore use function tables. But what's the advantage of using function table? Thanks, Mike
9
3462
by: christer-sandberg | last post by:
When I typecast a function and call it trough the casted pointer (se code below) I get the warnings: warning: function called through a non-compatible type if this code is reached, the program will abort and the gcc generates abort code for the call. This happens when I use gcc 3.4 but not when I use 3.3. Is there any flag that can change this behavior? I am aware that ANSI-99 says (in 6.3.2.3-8): "If a converted pointer is used to call...
3
9793
by: robin liu | last post by:
What's the difference between these two declarations ? 1) typedef void (*pf)(void); 2) typedef void f(void); the first declaration is define a function pointer, what is the second ? define a function model? And can use the second declaration to define a function pointer as follow:
5
3631
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call 10 member functions. Can switch be replaced to member function pointer array? Please provide me an example of source code to show smart pointer inside class. Thanks....
11
1487
by: ram kishore | last post by:
What is the difference between (int *) fun() and int *fun() ? What is the advantage of pointers to functions?
0
7979
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7894
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
5847
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5437
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3893
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3937
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2409
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1245
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.