-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-c-comment.c
86 lines (77 loc) · 1.89 KB
/
remove-c-comment.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* A simple hand-craft scanner (not a token) that will remove C styles of
* comment, interestingly C style does not allow nested forwardslash asterisk
* comment, so do this scanner, I shall add nested support sometimes later. :).
*/
#include <stdio.h>
#define YES 1
#define NO 0
/* simple program to remove comments from C
*/
int main(int argc, char *argv[]) {
int c;
int isInComment = NO;
int isCommentSingleLine = NO;
int isInQuote = NO;
int isPrevBackSlash = NO;
int prevC = '\0';
while ((c = getchar()) != EOF) {
if (isInComment) {
if ('/' == c) {
if ('*' == prevC) {
isInComment = NO;
prevC = '\0';
} else {
prevC = c;
}
} else if ('\n' == c && isCommentSingleLine) {
isInComment = NO;
isCommentSingleLine = NO;
putchar(c);
prevC = '\0';
} else {
prevC = c;
}
} else // if ( isInComment )
{
if (isInQuote) {
if ('\\' == c) {
isPrevBackSlash = YES;
} else {
if ('\'' == c) {
if (!isPrevBackSlash) {
isInQuote = NO;
}
}
isPrevBackSlash = NO;
}
putchar(c);
} else if ('\'' == c) {
isInQuote = YES;
putchar(c);
} else if ('/' == c) /* ... */
{
if ('/' == prevC) //
{
isInComment = YES;
isCommentSingleLine = YES;
} else {
prevC = c;
}
} else if ('*' == c) {
if ('/' == prevC) {
isInComment = YES;
isCommentSingleLine = NO;
}
prevC = '\0';
} else {
if ('\0' != prevC) {
putchar(prevC);
prevC = '\0';
}
putchar(c);
}
} // if ( isInComment ) ... else
} // while ( ( c = getchar() ) != EOF )
}