Skip to content

Instantly share code, notes, and snippets.

@jacobsebek
Last active February 6, 2022 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobsebek/d32ca1e50723e65d1c7c5a3651812099 to your computer and use it in GitHub Desktop.
Save jacobsebek/d32ca1e50723e65d1c7c5a3651812099 to your computer and use it in GitHub Desktop.
C/C++ comment remover
// Jakub Sebek, Feb 2022, Public Domain
// Please report bugs
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
int main() {
bool stresc = false, rawstring = false, multil = false;
char strend = false, rawend[16+2] = ")", *rawdc = NULL;
for (int l=EOF,c; (c = getchar()) != EOF;
!multil && c != EOF && putchar(c), l = c) {
if (multil) {
if (c != '*') continue;
while (l = getchar(), c = getchar(), l == '\\' && c == '\n');
ungetc(c, stdin); c = l;
if (c == '/') {
multil = false;
c = ' ';
} else ungetc(c, stdin); // fixes **/
continue;
}
if (rawstring) {
assert(rawdc - rawend < sizeof(rawend));
if (*rawdc == '\0' && c == '"') {
rawstring = false;
rawdc = NULL;
} else {
if (*rawdc++ != c) {
rawdc = rawend;
if (*rawdc == c) rawdc++; // fixes R"((..))"
}
continue;
}
} else if (rawdc) {
assert(rawdc - rawend + 1 < sizeof(rawend));
if ((*++rawdc = c) != '(') continue;
*rawdc = '\0';
rawstring = true;
rawdc = rawend;
} else if (!strend && l == 'R' && c == '"')
rawdc = rawend;
if ((strend && (c == strend || c == '\n') && !stresc) ||
(!strend && (c == '\'' || c == '"')))
strend = strend ? false : c;
if (strend)
stresc = (c == '\\' && l != '\\');
else if (c == '/') {
int escs = 0;
while (l = getchar(), c = getchar(), l == '\\' && c == '\n')
escs++;
ungetc(c, stdin); c = l;
if (c == '/')
while (c = getchar(), c != EOF && (c != '\n' || l == '\\'))
l = c;
else if (c == '*') multil = true;
else for (putchar('/'); escs--; puts("\\"));
}
}
assert(!multil); assert(!rawstring); assert(!rawdc); assert(!strend);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment