Sunday, August 28, 2011

Exercise 1-23

Exercise 1-23  Write a program to remove all comments from a C program.  Don't forget to handle quoted strings and character constants properly.  C comments do not nest.

I used function pointers for this, which may not be the best solution.

#include <stdio.h>
  /* Function prototypes. */
void normal(char c);
void backslash(char c);
void open_slash(char c);
void in_comment(char c);
void close_asterisk(char c);
void in_double_quotes(char c);
void in_single_quotes(char c);
void backslash_double(char c);
void backslash_single(char c);
  /* Our function pointer. */
void (*state)(char c);
void normal(char c)
{
  if (c=='/')
    state = open_slash;
  else
  {
    if (c=='\'')
      state = in_single_quotes;
    else if (c=='\"')
      state = in_double_quotes;
    putchar(c);
  }
}
void backslash_double(char c)
{
  /* Ignore the next character. */
  state = in_double_quotes;
}
void backslash_single(char c)
{
  /* Ignore the next character. */
  state = in_single_quotes;\
}
void open_slash(char c)
{
  if (c=='*')
    state = in_comment;
  else if (c=='/')
    putchar('/');
  else
  {
    putchar('/');
    putchar(c);
    state = normal;
  }
}
void in_comment(char c)
{
  if (c=='*')
    state = close_asterisk;
}
void close_asterisk(char c)
{
  if (c=='/')
    state = normal;
  else if (c!='*')
    state = in_comment;
  /* else state = close_asterisk; */
}
void in_double_quotes(char c)
{
  if (c=='"')
    state = normal;
  if (c=='\\')
    state = backslash_double;
  putchar(c);
}
void in_single_quotes(char c)
{
  if (c=='\'')
    state = normal;
  if (c=='\\')
    state = backslash_single;
  putchar(c);
}
int main(void)
{
  int c;
  state = normal;
  while (c = getchar(), c!=EOF)
    (*state)(c);
  /* We could warn the user about an unclosed comment,
   * or single or double quotes. */
  return 0;
}

No comments:

Post a Comment