OOC:en:3.1 The Main Loop
来自 ChinaUnix Wiki
The main loop of the program reads a line from standard input, initializes things so that numbers and operators can be extracted and white space is ignored, calls up a function to recognize a correct arithmetic expression and somehow store it, and finally processes whatever was stored. If things go wrong, we simply read the next input line. Here is the main loop:
#include <setjmp.h>
static enum tokens token; /* current input symbol */
static jmp_buf onError;
int main (void)
{ volatile int errors = 0;
char buf [BUFSIZ];
if (setjmp(onError))
++ errors;
while (gets(buf))
if (scan(buf))
{ void * e = sum();
if (token)
error("trash after sum");
process(e);
delete(e);
}
return errors > 0;
}
void error (const char * fmt, ...)
{ va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap), putc(’\n’, stderr);
va_end(ap);
longjmp(onError, 1);
}
The error recovery point is defined with setjmp().If error() is called somewhere in the program, longjmp() continues execution with another return from setjmp().In this case, the result is the value passed to longjmp(), the error is counted, and the next input line is read. The exit code of the program reports if any errors were encountered.
