Function Pointers

N

noridotjabi

What is the purpose of the function pointer? Why do you need a pointer
to a function. I cannot really think of any application where this is
the only or even easiest solution to a problem. I'm sure there are
really good aplications for it I just cannot think of any, so if anyone
can tell me why a pointer to a function is nessisary and when it
can/should be used I would apreciate that. Thanks.
Nori
 
A

Andrew Poelstra

What is the purpose of the function pointer? Why do you need a pointer
to a function. I cannot really think of any application where this is
the only or even easiest solution to a problem. I'm sure there are
really good aplications for it I just cannot think of any, so if anyone
can tell me why a pointer to a function is nessisary and when it
can/should be used I would apreciate that. Thanks.
Nori

Arrays of functions can be useful for menus, etc. Or, when writing
a bytecode interpreter:

func[bytecode]();
 
D

Default User

What is the purpose of the function pointer? Why do you need a
pointer to a function. I cannot really think of any application
where this is the only or even easiest solution to a problem. I'm
sure there are really good aplications for it I just cannot think of
any, so if anyone can tell me why a pointer to a function is
nessisary and when it can/should be used I would apreciate that.
Thanks. Nori


See qsort().




Brian
 
J

Jack Klein

What is the purpose of the function pointer? Why do you need a pointer
to a function. I cannot really think of any application where this is
the only or even easiest solution to a problem. I'm sure there are
really good aplications for it I just cannot think of any, so if anyone
can tell me why a pointer to a function is nessisary and when it
can/should be used I would apreciate that. Thanks.
Nori

The purpose of a pointer to a function is to hold the address of a
function, and quite possibly to call that function via the pointer.

Open your C book or reference and read about the standard library
functions qsort() and bsearch(). They are also useful in many other
types of coding.

As for whether you ever need function pointers, that depends on the
type of code you write, and also whether you ever intend to use the
standard qsort() or bsearch() functions.

If you don't want to use function pointers, you don't have to,
provided that you don't call any standard or third party library
functions that need them.
 
F

Frederick Gotham

(e-mail address removed) posted:
What is the purpose of the function pointer? Why do you need a pointer
to a function. I cannot really think of any application where this is
the only or even easiest solution to a problem. I'm sure there are
really good aplications for it I just cannot think of any, so if anyone
can tell me why a pointer to a function is nessisary and when it
can/should be used I would apreciate that. Thanks.
Nori


I've always thought Microsoft's "EnumWindows" was a good example.

Here's some sample code:


#include <stdio.h>
#include <stdlib.h>

void ComputePrimeNumbers( void (*Callback)(unsigned long) )
{
Callback(1);

unsigned long i;

unsigned long num = 3;

do
{
for( i = 2 ; ; )
{
if ( !(num % i) ) break;

if ( ++i == num )
{
Callback(num);
break;
}
}

} while ( ++num );
}

void Print( unsigned long const num )
{
printf( "%lu\n", num );
}

#include <cstdlib>

int main(void)
{
ComputePrimeNumbers( Print );

system("PAUSE");
}
 
F

Frederick Gotham

Frederick Gotham posted:

Here's some sample code:

Wups... I'll try that again:

#include <stdio.h>
#include <stdlib.h>

void ComputePrimeNumbers( void (*Callback)(unsigned long) )
{
unsigned long i;

unsigned long num = 3;

Callback(1);

do
{
for( i = 2 ; ; )
{
if ( !(num % i) ) break;

if ( ++i == num )
{
Callback(num);
break;
}
}

} while ( ++num );
}

void Print( unsigned long const num )
{
printf( "%lu\n", num );
}


int main(void)
{
ComputePrimeNumbers( Print );

system("PAUSE");

return 0;
}
 
R

Richard Heathfield

Frederick Gotham said:

<snip>

[...listing of code ends with...]
#include <cstdlib>

int main(void)
{
ComputePrimeNumbers( Print );

system("PAUSE");
}

foo.c:33: cstdlib: No such file or directory
 
R

Richard Heathfield

Frederick Gotham said:
Frederick Gotham posted:



Wups... I'll try that again:

#include <stdio.h>
#include <stdlib.h>

void ComputePrimeNumbers( void (*Callback)(unsigned long) )
{
unsigned long i;

unsigned long num = 3;

Callback(1);

1 is not prime.

system("PAUSE");

sh: PAUSE: command not found

Was that what you intended?
 
C

Charles Richmond

What is the purpose of the function pointer? Why do you need a pointer
to a function. I cannot really think of any application where this is
the only or even easiest solution to a problem. I'm sure there are
really good aplications for it I just cannot think of any, so if anyone
can tell me why a pointer to a function is nessisary and when it
can/should be used I would apreciate that. Thanks.
Fortunately, your lack of imagination does *not* constrain the C
standard in any way... ;-)
 
T

Tom Plunket

noridotjabi said:
What is the purpose of the function pointer?

To keep a pointer to a function, of course!
Why do you need a pointer to a function.

The way I use them mostly is in the implementation of state machines.

For example, in a (modern video-)game you've got a lot of objects
moving around and doing things. Generally each object can go about
its business without worrying about any other object. So, if I store
a function pointer in the object, in the main update loop I don't need
to worry about what the object should be doing... Be sure to catch
the main_game_loop() function at the bottom!

struct GameObject
{
struct GameObject* target;
void (*state)(struct GameObject*);
struct GameObject* next;
}

void eat(struct GameObject* go);
void sleep(struct GameObject* go);

void eat(struct GameObject* go)
{
PlayAnimation(go, "eat");

if (go->target != NULL)
{
/* 1 hit-point of damage to the target per game loop */
ApplyDamage(go->target, 1);
if (IsDead(go->target))
{
/* target will destroy itself in its update */
go->target = NULL;

go->state = sleep;
}
}
}

void sleep(struct GameObject* go)
{
PlayAnimation(go, "sleep")
if (go->target != NULL)
{
/* Uh oh, we've been awakened by an enemy! */
go->state = eat;
}
}

void main_game_loop(void)
{
GameObject* go;

for (go = theGameObjectList; go != NULL; go = go->next)
{
go->state(go);
}
}

I'm sure we can all see how easy game programming is! :)
-tom!
 
M

Morris Dovey

(e-mail address removed) (in
(e-mail address removed)) said:

| What is the purpose of the function pointer? Why do you need a
| pointer to a function. I cannot really think of any application
| where this is the only or even easiest solution to a problem. I'm
| sure there are really good aplications for it I just cannot think
| of any, so if anyone can tell me why a pointer to a function is
| nessisary and when it can/should be used I would apreciate that.

A real world application. A client wanted to describe the internal
behaviors of several lines of appliances using spreadsheets. I wrote
an application to process the spreadsheets and output a binary
pseudo-machine executable for each mode of operation of the described
appliance - as well as the necessary C programs to emulate the
pseudo-machine. This reduced the hand-written code to small
(appliance-specific) device drivers.

The emulator extracted op code and parameters from each p-code
instruction, used the op code as the index into an array of function
pointers, and passed the extracted parameters to the pointed-to
function. The code for the emulator engine was shorter than my
response to you.

This approach to automated control software production allowed a
design engineeer to revise his spread sheet, produce and compile the
uC code, and run a product test in less than an hour - and the
development package could be used for washing machines, dryers,
dishwashers, refrigerators (and more).

It'd have been difficult to do without using a table of function
pointers in the operation dispatcher. :)
 
F

Frederick Gotham

Richard Heathfield posted:

sh: PAUSE: command not found

Was that what you intended?


Sorry, not sure what you mean. I tend to put:

system("PAUSE");

at the end of my code snippets because a lot of people use Windows; and on
Windows, a console windows disappears once the program has finished
execution.

It's just for convenience so that my snippets are easy to compile straight-
out-of-the-box.
 
J

Joshua Shinavier

What is the purpose of the function pointer? Why do you need a pointer
to a function.

If C didn't have function pointers, it would be a lot less interesting
IMO. Function pointers give you the means to construct higher-order
functions which deal with things like polymorphism and graph
transformations. GNU C's nested functions are a whole other level of
joy, but these are nonstandard so I won't mention them here :)
 
A

Andrew Poelstra

Richard Heathfield posted:




Sorry, not sure what you mean. I tend to put:

system("PAUSE");

at the end of my code snippets because a lot of people use Windows; and on
Windows, a console windows disappears once the program has finished
execution.

I went onto my Windows box and ran a few programs. None of them closed the
console when they were done.
It's just for convenience so that my snippets are easy to compile straight-
out-of-the-box.

Considering that the Standard says pretty much nothing about what system() does,
I'm not sure how calling it would change how easy it is to compile something.
 
W

William Ahern

Richard Heathfield posted:



Sorry, not sure what you mean. I tend to put:

system("PAUSE");

at the end of my code snippets because a lot of people use Windows; and on
Windows, a console windows disappears once the program has finished
execution.

It's just for convenience so that my snippets are easy to compile
straight- out-of-the-box.

I think what he meant was, what if this happened:

sh: PAUSE: destroying orbital craft

Alas, such a scenario likely won't come to pass. But here in comp.lang.c,
we console ourselves with the conviction it's not entirely impossible.
 
A

ab

oops,that's C++,
in c, you should be this:
#include <stdlib.h>
int main(void)
{
...............................
return 0; /* or exit(0); */
}

Richard Heathfield 写é“:
Frederick Gotham said:

<snip>

[...listing of code ends with...]
#include <cstdlib>

int main(void)
{
ComputePrimeNumbers( Print );

system("PAUSE");
}

foo.c:33: cstdlib: No such file or directory


--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
 
K

Keith Thompson

Frederick Gotham said:
Richard Heathfield posted:


Sorry, not sure what you mean. I tend to put:

system("PAUSE");

at the end of my code snippets because a lot of people use Windows; and on
Windows, a console windows disappears once the program has finished
execution.

It's just for convenience so that my snippets are easy to compile straight-
out-of-the-box.

It doesn't affect ease of compilation. It might make them run in a
friendlier manner on Windows, but it's likely to cause an error
message similar to the one above on any other platform -- unless there
happens to be a "PAUSE" command, in which case it will do whatever
nasty thing that command happens to do.

There *should* be an easy way to execute a simple C program and see
its output. If Windows makes that difficult, that difficulty, or
system-specific workarounds for it, shouldn't be imposed on the rest
of us. (And of course you can always open a window and run the
program from the command line, or use whatever function your IDE
provides to run a program and see its output.)

But if you must cater to this Windows bug, there is a portable way to
do it: replace
system("PAUSE");
with
getchar();
 
R

Richard Heathfield

Frederick Gotham said:
Richard Heathfield posted:




Sorry, not sure what you mean. I tend to put:

system("PAUSE");

at the end of my code snippets because a lot of people use Windows;

True enough, but a lot of people don't use Windows, too, and on such systems
the PAUSE command may not exist, or may not do what you were hoping it did.
and on Windows, a console windows disappears once the program has
finished execution.

Not if you're running the program from within a console, it doesn't. And the
best way to run a console program is from within a console.
It's just for convenience so that my snippets are easy to compile
straight- out-of-the-box.

Oh, I have no issue with the compilation aspect. It's just the runtime
semantics I'm concerned about.
 
F

Frederick Gotham

Keith Thompson posted:

It doesn't affect ease of compilation.


I meant something more like:

easy to compile and execute straight-out-of-the-box.

It might make them run in a
friendlier manner on Windows, but it's likely to cause an error
message similar to the one above on any other platform -- unless there
happens to be a "PAUSE" command, in which case it will do whatever
nasty thing that command happens to do.

There *should* be an easy way to execute a simple C program and see
its output. If Windows makes that difficult, that difficulty, or
system-specific workarounds for it, shouldn't be imposed on the rest
of us. (And of course you can always open a window and run the
program from the command line, or use whatever function your IDE
provides to run a program and see its output.)


Acknowledged. I suppose I'll just twiddle my OS settings to make the
console app's stay visible upon termination, and hope that others do the
same.
 
R

Richard Heathfield

Keith Thompson said:

But if you must cater to this Windows bug, there is a portable way to
do it: replace
system("PAUSE");
with
getchar();

What a gerharsterly idea.

This whole thing is only really a problem if people launch console
applications via, say, Windows Explorer, instead of opening a console in
which to run the program.

Perhaps it would be wiser simply to add a console session to the Windows
startup sequence, which is easily done. Simply copy the Command Prompt
shortcut from the Accessories submenu to the Startup submenu. The details
of this are of course off-topic here, but no doubt a Windows support
newsgroup would be able to help (and really, it's extremely simple!).
 

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
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top