Sep 3, 2016

K & R : Exercise 1.23 - remove C comments

K & R : Exercise 1.23-remove C comments

Problem

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.


Solution

We need to remove all the C comments. There are two types of comments

  1. /* */
  2. //

We should not remove it when we are inside a string. Strings are always found inside "". First we need to find whether we are inside a sting. If we are inside a string we should not apply the C comment removal method. We need to remove all the characters inside /* */ it and replace it with white-space. And all the charters inside // till end of the line and replace it with space and newline.

Putting all the above idea into C program it would look as follows

#include <stdio.h>

enum com_type_t { NOT_COMMENT = 0,
                  COMMENT_SINGLE_LINE = 1,
                  COMMENT_MULTI_LINE = 2};

#define is_not_com() (com == NOT_COMMENT)

int main()
{
  int is_str = 0;
  int ch = -1, pch = -1;
  enum com_type_t com = NOT_COMMENT;

  while((ch = getchar()) != EOF) {
    if(ch == '"' && is_not_com()){
      is_str = ~is_str;
    }
    if(!is_str &&
       is_not_com() &&
       ch == '/' &&
       pch == '/') {
      com = COMMENT_SINGLE_LINE;
    }else if(!is_str &&
             is_not_com() &&
             ch == '*' &&
             pch == '/') {
      com = COMMENT_MULTI_LINE;
    }
    if(is_not_com() && pch != -1) {
      putchar(pch);
    }
    if(!is_str &&
             com == COMMENT_SINGLE_LINE &&
             ch == '\n') {
      putchar(' ');
      com = NOT_COMMENT;
    }else if(!is_str &&
             com == COMMENT_MULTI_LINE &&
             ch == '/' &&
             pch == '*') {
      ch = ' ';
      com = NOT_COMMENT;
    }
    pch = ch;
  }

}

No comments :

Post a Comment