I have understood the entire functionality of this program except the way it handles a nested comment input. The functionality of the State Star is unclear to me. What does c!='*' imply?
Suppose the input is haha /* hello /*world */, then after the first star if a slash comes, the control shifts to the PROGRAM state. however why is it accounting for c!='*'?
#include<stdio.h>
#include<conio.h>
void main()
{
enum{ /*Enum construct declares states */
PROGRAM,
SLASH,
STAR,
QUOTE,
COMMENT,
LITERAL
}state;
/* If state is quote then its either " or '*/
state = PROGRAM;
for(;;)
{
int c = getchar();
int quote = 0 ;
switch(state) {
case SLASH:
/* Program text following a slash */
if (c == '*') {
state = COMMENT;
break;
}
putchar('/');
state = PROGRAM;
case PROGRAM:
/*Program Text*/
if (c == '\''||c == '"') {
state = QUOTE;
quote = c;
putchar(quote);
}
else if (c == '/')
state = SLASH;
else
putchar(c);
break;
case COMMENT:
/* Comment */
if (c == '*')
state = STAR;
break;
case STAR:
/*Comment following a Star */
if (c == '/')
state = PROGRAM;
else if (c != '*') {
state = COMMENT;
putchar(' ');
}
break;
case QUOTE:
/*Within a quote or a string */
putchar(c);
if (c == '\\')
state = LITERAL;
else if (c == quote)
state = PROGRAM;
break;
case LITERAL:
/*Within a literal having /*/
putchar(c);
state = QUOTE;
break;
}
}
printf("Can it handle this /* I wonder */");
getch();
}
It’s to cope with input like this:
If you reverted to
COMMENTat the point I’ve marked, then you wouldn’t be looking for the/in order to revert toPROGRAM. You need to stay inSTAR.