Coroutines in C

Bill Poser poser at csli.Stanford.EDU
Wed Aug 16 08:45:34 AEST 1989


Another application of the same sorts of facilities used to implement
coroutines is for generator functions, i.e. functions that generate
a new member of some set each time they are called. Such functions are
useful for pattern matching. I have also found them useful when I
needed to obtain strings contained in heterogeneous data structures
(e.g. arrays and hash tables containing different kinds of objects)
and sort and format information coming from all of them. To get
each string you call the generator function for one of the types of
data. The generator functions know the details of how the data is
stored and how to traverse the data structure. But they all return
objects of the same type (strings) and you keep control over
storage allocation, sorting, formatting etc. in one place.

Generator functions can be implemented by hand by using static variables
to save the necessary state information, but this gets hairy very
quickly. If one can suspend the function rather than return from
it (which means, essentially, saving the stack frame) generators
easy to write. This is a nice facility of ICON.
 



More information about the Comp.lang.c mailing list