Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created July 6, 2013 03:23
Show Gist options
  • Save EdgeCaseBerg/5938505 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/5938505 to your computer and use it in GitHub Desktop.
Exercise 1-23 from The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie. Problem statement in gist. And yes, there is a goto in this code. This is an acceptable goto as a normal continue statement will not work due to the scope of the looping. If you still subscribe to religious dogmatism of the evils of a goto, then please refer …
#include <stdio.h>
/* 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 */
main(){
int first,second ,eatChar,lookAhead,previous;
first = getchar();
while((second = getchar()) != EOF){
if(first == '/')
if(second == '/'){
//Delete til the end of the line
while((eatChar=getchar())!=EOF && eatChar != '\n')
;
//Print the newline
putchar(eatChar);
}else if(second == '*'){
//Bit harder, read until the next */
while((eatChar = getchar()) != EOF){
if(eatChar == '*'){
lookAhead = getchar();
if(lookAhead == '/')
goto next;
else if(lookAhead == '*')
ungetc(first,stdin);
}
}
}
next:
if(first == '/' && second =='/')
;
else if(first == '/' && second == '*')
;
else if(previous == '/' && first == '/')
;
else if(previous == '/' && first == '*')
;
else
putchar(first);
previous=first;
first=second;
}
putchar(first);
printf("\n");
}
@EdgeCaseBerg
Copy link
Author

To Run:

$cc c_comment_removal.c
$./a.out < fileToRemoveCCommentsFrom.c > newlyformattedfile.c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment