For Programmers: Free Programming Magazines  


Home > Archive > C > June 2006 > Function Pointers









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Function Pointers
noridotjabi@gmail.com

2006-06-28, 6:56 pm

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

Andrew Poelstra

2006-06-28, 6:56 pm

On 2006-06-28, noridotjabi@gmail.com <noridotjabi@gmail.com> wrote:
> 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[i]]();

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Default User

2006-06-28, 6:56 pm

noridotjabi@gmail.com wrote:

> 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
Jack Klein

2006-06-28, 6:56 pm

On 28 Jun 2006 14:40:56 -0700, "noridotjabi@gmail.com"
<noridotjabi@gmail.com> wrote in comp.lang.c:

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

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~.../FAQ-acllc.html
Frederick Gotham

2006-06-28, 6:56 pm

noridotjabi@gmail.com 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");
}


--

Frederick Gotham
Frederick Gotham

2006-06-28, 6:56 pm

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;
}



--

Frederick Gotham
Richard Heathfield

2006-06-28, 6:56 pm

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)
Richard Heathfield

2006-06-28, 6:56 pm

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.

<snip>
>
> system("PAUSE");


sh: PAUSE: command not found

Was that what you intended?

--
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)
Charles Richmond

2006-06-28, 6:56 pm

"noridotjabi@gmail.com" wrote:
>
> 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... ;-)


--
+----------------------------------------------------------------+
| Charles and Francis Richmond richmond at plano dot net |
+----------------------------------------------------------------+
Tom Plunket

2006-06-28, 6:56 pm

noridotjabi wrote:

> 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!
Morris Dovey

2006-06-28, 6:56 pm

noridotjabi@gmail.com (in
1151530856.932637.131320@75g2000cwc.googlegroups.com) 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. :-)

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto


Frederick Gotham

2006-06-28, 6:56 pm

Richard Heathfield posted:


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



--

Frederick Gotham
Joshua Shinavier

2006-06-28, 6:56 pm

noridotjabi@gmail.com wrote:
> 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 :-)

Andrew Poelstra

2006-06-28, 9:56 pm

On 2006-06-29, Frederick Gotham <fgothamNO@SPAM.com> wrote:
> 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.

--
Andrew Poelstra <http://www.wpsoftware.net/blog>
To email me, use "apoelstra" at the above address.
"You people hate mathematics." -- James Harris
ab

2006-06-28, 9:56 pm

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

Richard Heathfield =E5=86=99=E9=81=93=EF=BC=9A

> Frederick Gotham said:
>
> <snip>
>
> [...listing of code ends with...]
>
>
> 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)


William Ahern

2006-06-28, 9:56 pm

On Thu, 29 Jun 2006 00:44:56 +0000, Frederick Gotham wrote:
> 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.

Keith Thompson

2006-06-28, 9:56 pm

Frederick Gotham <fgothamNO@SPAM.com> writes:
> 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();

--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Richard Heathfield

2006-06-28, 9:56 pm

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.

--
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)
Frederick Gotham

2006-06-28, 9:56 pm

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.


--

Frederick Gotham
Richard Heathfield

2006-06-28, 9:56 pm

Keith Thompson said:

<snip>
>
> 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!).

--
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)
pete

2006-06-28, 9:56 pm

Andrew Poelstra wrote:
>
> On 2006-06-29, Frederick Gotham <fgothamNO@SPAM.com> wrote:

"PAUSE" is not a portable system command.
In other words, it won't work on all systems.
The code you post here, should not be undefined.
Learnig how best to write portable or correct code,
is pretty much the whole point of reading this newgroup.

N869
3. Terms and definitions
3.18
[#1] undefined behavior
behavior, upon use of a nonportable or erroneous program
construct, of erroneous data, or of indeterminately valued
objects, for which this International Standard imposes no
requirements

4. Conformance
[#3] A program that is correct in all other aspects,
operating on correct data, containing unspecified behavior
shall be a correct program and act in accordance with
5.1.2.3.


[color=darkred]

Seriously, is it out of consideration for others,
and not because of a problem that you have?
[color=darkred]
>
> I went onto my Windows box and ran a few programs.
> None of them closed the
> console when they were done.


It doesn't happen on my windows box
when I open a command prompt window either.
It happened when I ran a program directly from MSVC
by clicking on an icon that looks like a red exclamation mark,
but I don't do that anymore.


No. That's not the reason.
It doesn't make the code easier to compile.
[color=darkred]
>
> 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.


--
pete
lovecreatesbeauty

2006-06-29, 6:56 pm


noridotjabi@gmail.com wrote:
> What is the purpose of the function pointer? Why do you need a pointer
> to a function.


A function pointer is used to pass a function without firing it. A
pointer provides an alternative way to access an object or a function.

> I cannot really think of any application where this is
> the only or even easiest solution to a problem.


A more complex example with function pointers is the function:

#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);

lovecreatesbeauty

Ben C

2006-06-29, 6:56 pm

On 2006-06-28, noridotjabi@gmail.com <noridotjabi@gmail.com> wrote:
> 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.


They're often useful when you have complicated data structures that you
want to iterate through. You write the function that finds its way
through the data structure once, and it calls a callback for each item
inside.

Something like this:

typedef int (*callback_t)(const struct record *record, void *handle);
extern int database_foreach(const struct database *db, callback_t cb);

Because database_foreach calls back whatever I pass in cb, I can use it
for all kinds of things without worrying how things are actually
arranged in the database and how to retrieve them. That code is written
once in database_foreach, and hidden away.

A common way to do this without callbacks, on the other hand, is
something like this:

extern db_iterator *database_start(const struct database *db);
extern const struct record *database_next(const struct database *db,
db_iterator *it);

Here the database code stores everything it needs to know about where it
got to and how to continue the iteration in *it, some kind of object it
creates specially to store this state in. In practice the contents of
*it will be the same sorts of things as are in the stack frame of
database_foreach.

On the other hand if you use database_foreach, the "handle" it calls
back the callback with will in many cases point to an object storing
state for whatever's going on "at the other end".

These are sometimes described as ways to "simulate coroutines in C". You
often find function pointers used in this kind of coroutine situation--
two or more operations which each need their own state and which work
together.
Clever Monkey

2006-06-29, 6:56 pm

noridotjabi@gmail.com wrote:
> 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
>

[Disclaimer: I'm no wizard, but I have been handed a pile of decades-old
C code to maintain. I do what I can with what I have!]

We use function pointers in a few places to implement callbacks. This
allows a variety of calling contexts to run code that can "call back" to
that context to update the UI, get input, read properties &etc.

All without the called code having to know who is calling it.

In this specific case we have a sort of API call that can update the UI
to handle exceptional cases requiring interaction (e.g., "Are you sure
you want to destroy Orbital Death Lasers? (y/N)"), regardless of what
sort of UI that is. Add a UI/interface and all you have to do is change
the code you set the function pointer to -- you do not have to change
code that *other* UIs and interfaces may rely on.

Another use is when implementing a classic data structure like a map or
list. It is common enough for for the sort, search or compare functions
one needs for the data structure to be implemented as a pointer to a
function. This is a similar use to the standard qsort().
Roberto Waltman

2006-06-29, 6:56 pm

<noridotjabi@gmail.com> wrote:

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


Others already provided good answers. I thought a simple example would
complement them. A common use of function pointers is in table driven
command interpreters.
Let's say you need to write a CD player that is controlled by typing
commands such as "start", "next", etc.
The following could be the core of that program. Should be self
explanatory.

=================================

#include <stdio.h>
#include <string.h>

#define GOOD 1
#define BAD 0

void f_start (void);
void f_stop (void);
void f_pause (void);
void f_resume(void);
void f_next (void);
void f_prev (void);


struct cmd_row
{
char *cmd; /* command name */
char *help; /* command description */
void (*func)(void);/* function to call */
};


struct cmd_row cmd_table[] =
{
{"start", "start playback", f_start },
{"stop", "stop playback", f_stop },
{"pause", "pause playback", f_pause },
{"resume", "resume playback",f_resume},
{"next", "next track", f_next },
{"prev", "previous track", f_prev },
{NULL, NULL, NULL }
};


int cmd_run(char *cmd)
{
struct cmd_row *row = cmd_table;

if (!cmd)
{
return BAD;
}

while (row->cmd)
{
if (!strcmp(cmd, row->cmd))
{
puts(row->help);
(row->func)();
return GOOD;
}
row++;
}
return BAD;
}

=================================
Ben C

2006-06-29, 6:56 pm

On 2006-06-29, Roberto Waltman <usenet@rwaltman.net> wrote:
><noridotjabi@gmail.com> wrote:
>
>
> Others already provided good answers. I thought a simple example would
> complement them. A common use of function pointers is in table driven
> command interpreters.
> Let's say you need to write a CD player that is controlled by typing
> commands such as "start", "next", etc.
> The following could be the core of that program. Should be self
> explanatory.
>
>=================================
>
> #include <stdio.h>
> #include <string.h>
>
> #define GOOD 1
> #define BAD 0
>
> void f_start (void);
> void f_stop (void);
> void f_pause (void);
> void f_resume(void);
> void f_next (void);
> void f_prev (void);
>
>
> struct cmd_row
> {
> char *cmd; /* command name */
> char *help; /* command description */
> void (*func)(void);/* function to call */
> };
>
>
> struct cmd_row cmd_table[] =
> {
> {"start", "start playback", f_start },
> {"stop", "stop playback", f_stop },
> {"pause", "pause playback", f_pause },
> {"resume", "resume playback",f_resume},
> {"next", "next track", f_next },
> {"prev", "previous track", f_prev },
> {NULL, NULL, NULL }
> };
>
>
> int cmd_run(char *cmd)
> {
> struct cmd_row *row = cmd_table;
>
> if (!cmd)
> {
> return BAD;
> }
>
> while (row->cmd)
> {
> if (!strcmp(cmd, row->cmd))
> {
> puts(row->help);
> (row->func)();
> return GOOD;
> }
> row++;
> }
> return BAD;
> }


This is a good example also of "data driven programming"-- try writing
this program without the function pointers and you probably end up with
a lot of conditions or switch statements.

I've seen some programs in which switch statements got really out of
hand. Use of function pointer tables is often an option for tidying them
up.

It's probably more efficient too:

If you write:

switch (state)
{
case SOMETHING:
do_something();
...
break
case BLAHBLAH:
do_something_else();
...
break
case ...

... lots and lots more case statements ...

the compiled program has to test the value of state against SOMETHING,
BLAHBLAH, and all the other labels, until it finds a match. If there are
a lot of labels this can be significant-- it is effectively a linear
search for the bit of code to execute. I suppose there's nothing
stopping the compiler building some sort of index for switch statements
with large numbers of cases, although I don't know if they do.

If you use:

fn = functions[state];
(*fn)();

on the other hand, fn is looked up at once by using state as an index.
Al Balmer

2006-06-29, 6:56 pm

On 29 Jun 2006 21:28:47 GMT, Ben C <spamspam@spam.eggs> wrote:

>the compiled program has to test the value of state against SOMETHING,
>BLAHBLAH, and all the other labels, until it finds a match. If there are
>a lot of labels this can be significant-- it is effectively a linear
>search for the bit of code to execute. I suppose there's nothing
>stopping the compiler building some sort of index for switch statements
>with large numbers of cases, although I don't know if they do.
>

They do :-) In fact, they can be downright clever about it, especially
when the case values are non-contiguous.

>If you use:
>
> fn = functions[state];
> (*fn)();
>
>on the other hand, fn is looked up at once by using state as an index.


Works well if the range of state values isn't too great. If they're
non-contiguous, you can set missing ones to NULL and test before
calling.

The best part is that generally the code becomes easier to read.

--
Al Balmer
Sun City, AZ
Tom Plunket

2006-06-29, 9:56 pm

Ben C wrote:

> This is a good example also of "data driven programming"-- try writing
> this program without the function pointers and you probably end up with
> a lot of conditions or switch statements.


I'd call it "table-oriented programming," if I wasn't afraid of
invoking TopMind. Maybe he doesn't hang out here though...

Building tables of homogenous data is incredibly useful, IMHO. Keeping
the data separate from the code is very important, and table-oriented
programming facilitates a large class of problems relating to that.

-tom!
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com