Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
Function Pointers
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
Reply to thread
Message
[QUOTE="Ben C, post: 2471985"] 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. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
Function Pointers
Top