Function pointer Advantage

R

Rajesh

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
 
N

Nils Petter Vaskinn

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)(const void *, const void *));
 
N

Nick Keighley

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.
 
J

John Bode

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.
 
A

Al Bowers

Rajesh said:
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***************/
 
T

Tom St Denis

Rajesh said:
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_homework == 1) {
a(some_data);
} else if (doing_my_homework == 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
 
E

Eric Sosman

Rajesh said:
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.
 
W

Wolfgang Riedel

Rajesh said:
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 = (xmlValidityErrorFunc) dummy;
ctxt->vctxt.warning = (xmlValidityWarningFunc) 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_verify(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_signature(p7, signcert, pkey, EVP_md5())))
/* (who needs lisp?)))) */

now it's md5 and not sha1

there's more, but those are some ideas.

Wolfgang
 
P

Peter Pichler

John Bode said:
(e-mail address removed) (Rajesh) wrote in message
No faster than calling the function directly.

That is probably true.
Depends on what you mean by "optimize". Probably not.

Using function pointers /may/ improve code maintainability. If that counts
as "optimisation" 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' :)
 
M

Malcolm

Peter Pichler said:
Using function pointers /may/ improve code maintainability. If that
counts as "optimisation" depends on the OP.
In programming "optimisation" 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.
 
N

Nils Petter Vaskinn

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

bzzt. Optimisation can mean more than one thing.

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

Another form would be to optimise for memory usage, that is make the
program produce the same output while requiering less memory to run.

Also depending on the task you can "optimise" for programmer time instead
of processor time. eg: I need a program that I will run once a month for a
year and then discard. Instead of implementing it as efficient as possible
I implement it as simple as possible (very often brute force approaches)
since the time spent making and debugging the perfect solution would be
more than the time spent waiting for the (simple but less efficient)
program to run.

You can also optimise for maintainability, that is choose a clear and
easily modifiable design over a potentially faster one.

And there are probably things I haven't thought of too.
 
J

Jeremy Yallop

Nils said:
bzzt. Optimisation can mean more than one thing.

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

Another form would be to optimise for memory usage, that is make the
program produce the same output while requiering less memory to run.

Also depending on the task you can "optimise" for programmer time instead
of processor time. eg: I need a program that I will run once a month for a
year and then discard. Instead of implementing it as efficient as possible
I implement it as simple as possible (very often brute force approaches)
since the time spent making and debugging the perfect solution would be
more than the time spent waiting for the (simple but less efficient)
program to run.

You can also optimise for maintainability, that is choose a clear and
easily modifiable design over a potentially faster one.

Common Lisp has standardized "optimize" declarations which can be
added to individual forms or at top level. The available "qualities"
for which the programmer can request optimization include:

compilation-speed speed of the compilation process
debug ease of debugging
safety run-time error checking
space both code size and run-time space
speed speed of the object code

http://www.lispworks.com/reference/HyperSpec/Body/d_optimi.htm

Jeremy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top