Code Fragment for a DFA Scanner
Both a next state and a current state variable are used. This gives the action code three pieces of information to work with: current state, next state, and the character just read.
The semantic actions go between the call to the NextState() function and the setting of the current state variable.
The character ch is read and end-of-file is tested after testing for an accepting state. We want the loop to end as soon as the DFA accepts.
Since the loop may end without being in an accepting state, code at the end of the loop must tidy up and decide what to return if that happens.
typedef enum { S_START, S_ACCEPT, S_ERROR, ... } State;
State current, next;
...
current = S_START;
while( current != S_ACCEPT && (ch=fgetc(fp)) != EOF ){
next = NextState(current,ch);
if( next == S_ERROR ){
/* handle the failure */
}
/* remaining semantic actions go here */
current = next;
}
switch( current ){
case S_START:
case S_ACCEPT:
case S_ERROR:
default:
}