Exercise 1.23 - Remove comments from a C program

Question

Write a program to remove all comments from a C program. Don’t forget to handle quoted strings and character constants properly. C comments don’t nest.

Solution

/*  Exercise 1.23
 *
 * Program to remove comments from a C Program.
 *
 * Program should echo quotes and character constants properly
 * C comments do not nest
 *
 */

#include <stdio.h>

void rcomment(int c);

void incomment(void);

void echo_quote(int c);

int main(void) {
    int c, d;

    printf(" To Check /* Quoted String */ \n");

    while ((c = getchar()) != EOF)
        rcomment(c);

    return 0;
}

void rcomment(int c) {
    int d;

    if (c == '/') {
        if ((d = getchar()) == '*')
            incomment();
        else if (d == '/') {
            putchar(c);
            rcomment(d);
        } else {
            putchar(c);
            putchar(d);
        }
    } else if (c == '\'' || c == '"')
        echo_quote(c);
    else
        putchar(c);
}

void incomment() {
    int c, d;

    c = getchar();
    d = getchar();

    while (c != '*' || d != '/') {
        c = d;
        d = getchar();
    }
}

void echo_quote(int c) {
    int d;

    putchar(c);

    while ((d = getchar()) != c) {
        putchar(d);

        if (d == '\\')
            putchar(getchar());
    }
    putchar(d);
}

Explanation

If two subsequent characters start with / and *, we say we are in-comment, If we find two characters which are / and /, we will print the first character and start treating the second / as the possible start of comment. In the same manner, if we encouter a single quote or a double quote character, then we understand we are inside a quoted string, so we putchar everything before we find the matching character again. Within a quoted string, if we encouter a special character, then we try to read them literally as two characters and print them.

If / is followed by any other character, we simply print them.