M> enum NextThing { GET, PRINT, BYEBYE };
GET==0
PRINT==1
BYEBYE==2
we use these to index into the ftable array
M> enum NextThing nextThing;
nextThing initialized to GET, so the get function is the first one we
call.
M> int ch;
M> void get()
M> {
M> ch = getc(stdin);
M> nextThing = (ch != EOF) ? PRINT : BYEBYE;
M> }
Read a character from stdin and save it in the global variable ch. If
we reached the end, call the byebye function on the next iteration,
else call the print function
M> void byebye() { exit(0); }
exit(0) quits the program. This will terminate the infinite loop down
in main
M> void print() { fputc(ch, stdout); nextThing = GET; }
print ch out and and call get on the next iteration to read another
character. You can see we are bouncing back and forth between get and
print until we reach the end of the stream.
M> void (* const ftable[])() = {
M> get,
M> print,
M> byebye
M> };
ftable[GET] == &get
ftable[PRINT] == &print
ftable[BYEBYE] == &byebye
To make the type easier to understand, you can also use typedefs:
typedef void (*FN)(void);
FN is a pointer to a function taking no parameters and returning
nothing
FN ftable[3] = { get, print, byebye };
ftable is a 3 element array of function pointers
M> int main()
M> {
M> for (;
M> ftable[nextThing]();
M> return 0;
M> }
I'm not sure I understood well - how will the function 'ftable[nextThing]()'
know what index to pickup? Could ypu please clear up this?
ftable is an array of function pointers (you can't create an array of
functions by the way for various reasons). You index it with nextThing
as the index. The print and get functions modify the nextThing index
depending on the state. For example:
void (*fnptr)() = ftable[1];
copies the function pointer at ftable[1] (&print in this case) over to
the variable fnptr. Now, we can call the function by using fnptr(). You
could have also called it without the temporary variable by using
ftable[1]().
You should probably step through this code with a debugger to examine
what's going on at each step if you still don't get it.