SUMIT said:
I wrote a program for removing comment from C source file for which
i...
1.first constructed a DFA
2.used goto statement to write a program.
now it was very easy to model DFA using goto & i suppose it was also
efficient.
so was the use of goto right here?
Other responders have given answers like "probably not",
"maybe", or "it depends". Here's another opinion: No.
I'll elaborate a bit on that two-letter answer.
First, there's an excellent chance the program you have now
is wrong. It's not too hard to remove C comments if one
ignores the corner cases, but dealing with the corner cases
adds noticeably to the complexity. Using goto doesn't scale
up very well as the DFA gets more complicated.
Second, even if it was clear to you when you wrote it, it
probably won't be so clear to the next guy, or yourself when
you have to look at it again later. Right now you've got
all the structure in your head; but someone who doesn't
have all the structure in their head will have to discover
it looking over the various goto's (presumably in a single
large function body).
Third, perhaps most important, there's a simple and clear
way to write the code that needs no goto's at all. Here's
a sketch:
int
main(){
State s;
int c;
s = NORMAL;
do {
c = getchar();
switch( s ){
case NORMAL: s = normal_next(c); break;
case STRING: s = string_next(c); break;
case STRING_1: s = string_1_next(c); break;
case CHARLIT: s = charlit_next(c); break;
case CHARLIT_1: s = charlit_1_next(c); break;
case SLASH: s = slash_next(c); break;
case COMMENT: s = comment_next(c); break;
case COMMENT_1: s = comment_1_next(c); break;
...
}
} while( c != EOF );
return appropriate_return_code();
}
State
normal_next( int c ){
if( c == '"' ){ out(c); return STRING; }
if( c == '\'' ){ out(c); return CHARLIT; }
if( c == '/' ){ return SLASH; }
...
out(c);
return NORMAL;
}
... etc ...
I expect a program along these lines would be somewhat
longer than the program you wrote, and probably take
slightly longer to write (because of typing time if nothing
else). However, when the time comes to fix or improve the
program, you'll be glad you took the time to structure the
code in a way that scales up better.
Incidentally, the removal of comments from C source cannot,
strictly speaking, be done with just a finite state machine
(aka DFA). Additional state (in principle unbounded) is
needed. (I'll just leave this topic here, without saying
why, in case some comp.lang.c readers would enjoy figuring
that out on their own.)