473,899 Members | 3,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to remove // comments

Recently, a heated debate started because of poor mr heathfield
was unable to compile a program with // comments.

Here is a utility for him, so that he can (at last) compile my
programs :-)

More seriously, this code takes 560 bytes. Amazing isn't it? C is very
ompact, you can do great things in a few bytes.

Obviously I have avoided here, in consideration for his pedantic
compiler flags, any C99 issues, so it will compile in obsolete
compilers, and with only ~600 bytes you can run it in the toaster!

--------------------------------------------------------------cut here

/* This program reads a C source file and writes it modified to stdout
All // comments will be replaced by /* ... */ comments, to easy the
porting to old environments or to post it in usenet, where
// comments can be broken in several lines, and messed up.
*/

#include <stdio.h>

/* This function reads a character and writes it to stdout */
static int Fgetc(FILE *f)
{
int c = fgetc(f);
if (c != EOF)
putchar(c);
return c;
}

/* This function skips strings */
static int ParseString(FIL E *f)
{
int c = Fgetc(f);
while (c != EOF && c != '"') {
if (c == '\\')
c = Fgetc(f);
if (c != EOF)
c = Fgetc(f);
}
if (c == '"')
c = Fgetc(f);
return c;
}
/* Skips multi-line comments */
static int ParseComment(FI LE *f)
{
int c = Fgetc(f);

while (1) {
while (c != '*') {
c = Fgetc(f);
if (c == EOF)
return EOF;
}
c = Fgetc(f);
if (c == '/')
break;
}
return Fgetc(f);
}

/* Skips // comments. Note that we use fgetc here and NOT Fgetc */
/* since we want to modify the output before gets echoed */
static int ParseCppComment (FILE *f)
{
int c = fgetc(f);

while (c != EOF && c != '\n') {
putchar(c);
c = fgetc(f);
}
if (c == '\n') {
puts(" */");
c = Fgetc(f);
}
return c;
}

/* Checks if a comment is followed after a '/' char */
static int CheckComment(in t c,FILE *f)
{
if (c == '/') {
c = fgetc(f);
if (c == '*') {
putchar('*');
c = ParseComment(f) ;
}
else if (c == '/') {
putchar('*');
c = ParseCppComment (f);
}
else {
putchar(c);
c = Fgetc(f);
}
}
return c;
}

/* Skips chars between simple quotes */
static int ParseQuotedChar (FILE *f)
{
int c = Fgetc(f);
while (c != EOF && c != '\'') {
if (c == '\\')
c = Fgetc(f);
if (c != EOF)
c = Fgetc(f);
}
if (c == '\'')
c = Fgetc(f);
return c;
}
int main(int argc,char *argv[])
{
FILE *f;
int c;
if (argc == 1) {
fprintf(stderr, "Usage: %s <file.c>\n",arg v[0]);
return EXIT_FAILURE;
}
f = fopen(argv[1],"r");
if (f == NULL) {
fprintf(stderr, "Can't find %s\n",argv[1]);
return EXIT_FAILURE;
}
c = Fgetc(f);
while (c != EOF) {
/* Note that each of the switches must advance the character */
/* read so that we avoid an infinite loop. */
switch (c) {
case '"':
c = ParseString(f);
break;
case '/':
c = CheckComment(c, f);
break;
case '\'':
c = ParseQuotedChar (f);
break;
default:
c = Fgetc(f);
}
}
fclose(f);
return 0;
}

Oct 19 '06
100 5175
Ben Bacarisse wrote:
jacob navia <ja***@jacob.re mcomp.frwrites:

>>Recently, a heated debate started because of poor mr heathfield
was unable to compile a program with // comments.

Here is a utility for him, so that he can (at last) compile my
programs :-)

More seriously, this code takes 560 bytes. Amazing isn't it? C is very
ompact, you can do great things in a few bytes.


You can do *some* things in 560 bytes. Great things, it seems need a
few more. You need to:

(a) include <stdlib.h>
yeah
(b) remove the nested comment.
yes
(c) fix the logic bugs.

On given the admittedly clumsy but valid:

return 1//* what divisor? */2;

This is the same as finding a spurious */ in
a cpp comment. Corrected
>
you program produces the invalid:

return 1/** what divisor? */2; */

And on the more plausible:

// I don't like */ delimiters

we get:

/* I don't like */ delimiters */
!!!!

Corrected, thanks
Oct 20 '06 #11
jacob navia wrote:
Walter Bright wrote:
>A trigraph case:

char* d = "??/""; // "

but of course I've never seen trigraphs outside of a test suite.
Me neither. But I do not support trigraphs anyway. They are an
unnecessary feature. We had several lebgthy discussions about this in
comp.std.c.
Trigraphs are a worthless feature. Nevertheless, they are in the
standard, and it's much less effort to implement them than it is to
constantly have to justify otherwise.

Aside from such trivial defects, overall the C standard was a vast
improvement over existing practice at the time: having multiple compiler
switches to be quirk-compatible with this or that dialect.
Oct 20 '06 #12
I edited the code before posting, without recompiling it.
Big mistake. I added a nested comment, and when replacing the
EXIT_FAILURE because of Keith's remarks in another thread
I forgot to add the stdlib.h include.

Besides, I have fixed the few logic bugs pointed out by you:
1) continuation lines that become comments
e.g. /\
/ comment
will become
/*
comment */
2) If a sequence */ is found in a cpp comment it will be replaced by
* /, i.e. a blank will be inserted. There is no other way to do that.
3) Trigraphs are NOT supported.

Thanks to all people that participated. Updated program below.
----------------------------------------------------cut here
#include <stdio.h>
#include <stdlib.h>
/* This function reads a character and writes it to stdout */
static int Fgetc(FILE *f)
{
int c = fgetc(f);
if (c != EOF)
putchar(c);
return c;
}

/* Skips strings */
static int ParseString(FIL E *f)
{
int c = Fgetc(f);
while (c != EOF && c != '"') {
if (c == '\\')
c = Fgetc(f);
if (c != EOF)
c = Fgetc(f);
}
if (c == '"')
c = Fgetc(f);
return c;
}
/* Skips multi-line comments */
static int ParseComment(FI LE *f)
{
int c = Fgetc(f);

while (1) {
while (c != '*') {
c = Fgetc(f);
if (c == EOF)
return EOF;
}
c = Fgetc(f);
if (c == '/')
break;
}
return Fgetc(f);
}

/* Skips // comments */
static int ParseCppComment (FILE *f)
{
int c = fgetc(f);

while (c != EOF && c != '\n') {
int last;
putchar(c);
last = c;
c = fgetc(f);
if (c == '/' && last == '*')
putchar(' ');
}
if (c == '\n') {
puts(" */");
c = Fgetc(f);
}
return c;
}

/* Checks if a comment is followed after a '/' char */
static int CheckComment(in t c,FILE *f)
{
c = fgetc(f);
if (c == '*') {
putchar('*');
c = ParseComment(f) ;
}
else if (c == '/') {
putchar('*');
c = ParseCppComment (f);
}
else if (c == '\\') {
c = fgetc(f);
if (c == '\n') {
c = fgetc(f);
if (c == '/') {
printf("*\n");
ParseCppComment (f);
}
else printf("\\\n%c" ,c);
}
else {
putchar('\\');
putchar(c);
}
}
else {
putchar(c);
c = Fgetc(f);
}
return c;
}

/* Skips chars between simple quotes */
static int ParseQuotedChar (FILE *f)
{
int c = Fgetc(f);
while (c != EOF && c != '\'') {
if (c == '\\')
c = Fgetc(f);
if (c != EOF)
c = Fgetc(f);
}
if (c == '\'')
c = Fgetc(f);
return c;
}
int main(int argc,char *argv[])
{
FILE *f;
int c;
if (argc == 1) {
fprintf(stderr, "Usage: %s <file.c>\n",arg v[0]);
return EXIT_FAILURE;
}
f = fopen(argv[1],"r");
if (f == NULL) {
fprintf(stderr, "Can't find %s\n",argv[1]);
return EXIT_FAILURE;
}
c = Fgetc(f);
while (c != EOF) {
/* Note that each of the switches must advance the character */
/* read so that we avoid an infinite loop. */
switch (c) {
case '"':
c = ParseString(f);
break;
case '/':
c = CheckComment(c, f);
break;
case '\'':
c = ParseQuotedChar (f);
break;
default:
c = Fgetc(f);
}
}
fclose(f);
return 0;
}
Oct 20 '06 #13
jacob navia <ja***@jacob.re mcomp.frwrites:
Ben Bacarisse wrote:
>jacob navia <ja***@jacob.re mcomp.frwrites:
>>>Recently, a heated debate started because of poor mr heathfield
was unable to compile a program with // comments.

Here is a utility for him, so that he can (at last) compile my
programs :-)

More seriously, this code takes 560 bytes. Amazing isn't it? C is very
ompact, you can do great things in a few bytes.
You can do *some* things in 560 bytes. Great things, it seems need a
few more. You need to:
(a) include <stdlib.h>
yeah
>(b) remove the nested comment.
yes
>(c) fix the logic bugs.
On given the admittedly clumsy but valid:
return 1//* what divisor? */2;

This is the same as finding a spurious */ in
a cpp comment.
I don't think so. The point of this test case is that it does not
*have* a CPP comment at all.
Corrected
No. Your new version produces:

return 1/** what divisor? * /2; */

(which is not a valid statement) from

return 1//* what divisor? */2;

which is, I think, a valid way to write return 1/2;

--
Ben.
Oct 20 '06 #14
Ben Bacarisse wrote:
jacob navia <ja***@jacob.re mcomp.frwrites:

>>Ben Bacarisse wrote:
>>>jacob navia <ja***@jacob.re mcomp.frwrites:
Recently, a heated debate started because of poor mr heathfield
was unable to compile a program with // comments.

Here is a utility for him, so that he can (at last) compile my
programs :-)

More seriously, this code takes 560 bytes. Amazing isn't it? C is very
ompact, you can do great things in a few bytes.

You can do *some* things in 560 bytes. Great things, it seems need a
few more. You need to:
(a) include <stdlib.h>

yeah

>>>(b) remove the nested comment.

yes

>>>(c) fix the logic bugs.
On given the admittedly clumsy but valid:
return 1//* what divisor? */2;

This is the same as finding a spurious */ in
a cpp comment.


I don't think so. The point of this test case is that it does not
*have* a CPP comment at all.

>>Corrected


No. Your new version produces:

return 1/** what divisor? * /2; */

(which is not a valid statement) from

return 1//* what divisor? */2;

which is, I think, a valid way to write return 1/2;
No. MSVC for instance will pre-proccess your statement to
return 1

without anything beyond the //
gcc will do the same
lcc-win32 will do the same

Oct 20 '06 #15
Ben Bacarisse wrote:
No. Your new version produces:

return 1/** what divisor? * /2; */

(which is not a valid statement) from

return 1//* what divisor? */2;

which is, I think, a valid way to write return 1/2;
Jacob has that right. //* is lexed as the start of a // comment, not a
divide followed by the start of a /* comment. It's the same reason that:

i/*p;
i++; /* comment */
*p+3;

is parsed as:

(i * p) + 3;

i.e. the maximal munch rule.

Walter Bright
www.digitalmars.com C, C++, D programming language compilers
Oct 20 '06 #16
jacob navia <ja***@jacob.re mcomp.frwrites:
Ben Bacarisse wrote:
>jacob navia <ja***@jacob.re mcomp.frwrites:
>>>Ben Bacarisse wrote:

jacob navia <ja***@jacob.re mcomp.frwrites:
>Recently , a heated debate started because of poor mr heathfield
>was unable to compile a program with // comments.
>
>Here is a utility for him, so that he can (at last) compile my
>programs :-)
>
>More seriously, this code takes 560 bytes. Amazing isn't it? C is very
>ompact, you can do great things in a few bytes.

You can do *some* things in 560 bytes. Great things, it seems need a
few more. You need to:
(a) include <stdlib.h>

yeah
(b) remove the nested comment.

yes
(c) fix the logic bugs.
On given the admittedly clumsy but valid:
return 1//* what divisor? */2;

This is the same as finding a spurious */ in
a cpp comment.
I don't think so. The point of this test case is that it does not
*have* a CPP comment at all.
>>>Corrected
No. Your new version produces:
return 1/** what divisor? * /2; */
(which is not a valid statement) from
return 1//* what divisor? */2;
which is, I think, a valid way to write return 1/2;

No. MSVC for instance will pre-proccess your statement to
return 1

without anything beyond the //
gcc will do the same
lcc-win32 will do the same
Yes, I had assumed you program would be "C89 safe", but I can see now that
there is no reasonable way that is could be.

--
Ben.
Oct 20 '06 #17
Walter Bright <wa****@digital mars-nospamm.comwrit es:
Ben Bacarisse wrote:
>No. Your new version produces:
return 1/** what divisor? * /2; */
(which is not a valid statement) from
return 1//* what divisor? */2;
which is, I think, a valid way to write return 1/2;

Jacob has that right. //* is lexed as the start of a // comment
Yes, ack'd already. I had stupidly thought the program should be C89
neutral, but the input will never be C89 if it has // intended as a
comment.

So, who wants to do moving declarations up to the top on the enclosing
block? :-)

--
Ben.
Oct 20 '06 #18
jacob navia wrote:
Besides, I have fixed the few logic bugs pointed out by you:
1) continuation lines that become comments
e.g. /\
/ comment
will become
/*
comment */
But the more likely

//\
comment

Won't work.

You also forgot the case:

#include <ftp://domain.com/myfile.h>

And your program output is very misleading when given the input:

#error // comments not allowed

Regards,
Bart.

Oct 20 '06 #19
Bart wrote:
jacob navia wrote:
>>Besides, I have fixed the few logic bugs pointed out by you:
1) continuation lines that become comments
e.g. /\
/ comment
will become
/*
comment */


But the more likely

//\
comment

Won't work.
Fixed
>
You also forgot the case:

#include <ftp://domain.com/myfile.h>
????
Well, URLs in #include directives...

Not yet.
And your program output is very misleading when given the input:

#error // comments not allowed
If they are not allowed...
Oct 20 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1790
by: qwweeeit | last post by:
For a python code I am writing I need to remove all strings definitions from source and substitute them with a place-holder. To make clearer: line 45 sVar="this is the string assigned to sVar" must be converted in: line 45 sVar=s00001 Such substitution is recorded in a file under: s0001="this is the string assigned to sVar"
3
2661
by: Markus | last post by:
Hi! I wanted to select a subset of nodes (list = selectNodes("parent/child") from a XmlDocument, then remove all (parentNode.removeAll();) child-nodes and insert the previous selected nodes back. Of course the XmlNodes in the nodelist ref. where lost once the removeAll() were executed, this is expected. So the obvious way to achive the result would be to clone the nodes or remove the nodes not qualifying the Xpath.
9
5763
by: Frank Potter | last post by:
I only want to remove the comments which begin with "//". I did like this, but it doesn't work. r=re.compile(ur"//+$", re.UNICODE|re.VERBOSE) f=file.open("mycpp.cpp","r") f=unicode(f,"utf8") r.sub(ur"",f) Will somebody show me the right way? Thanks~~
1
14354
by: Andrus | last post by:
I need to remove all comments ( between <!-- and --tags) from XML string. I tried the following code but comments are still present. Or is it better to open xml string with a StreamReader, read all the text inside and remove all the "<!--" and "-->" substrings? How to remove comments ? string RemoveComments(string sDoc) {
3
6295
by: Laurence | last post by:
Hi folks, How to remove the transaction logs which are out of date in HADR environment? DB2 command PRUNE, it can only run on primary database but cannot run on standby database. Because the database conection is not permitted on standby database. USEREXIT, I don't know whether it can run on standby database or
1
4307
by: Andrus | last post by:
I have SQL strings which contain comments starting with -- and continuing to end of line like string mystring=@"SELECT data, -- ending comment -- line comment FROM mytable "; How to remove comment from those strings ? I need to delete charactes starting from -- and ending with line end in
4
9873
by: FullBandwidth | last post by:
I have been perusing various blogs and MSDN pages discussing the use of event properties and the EventHandlerList class. I don't believe there's anything special about the EventHandlerList class in this context, in fact some articles from pre-2.0 suggest using any collection class of your choice. So my questions focus more on the syntax of event properties provided by the "event" keyword in C#. (Disclaimer - I am a C++ programmer working...
61
3313
by: arnuld | last post by:
I have created a program which creates and renames files. I have described everything in comments. All I have is the cod-duplication. function like fopen, sprint and fwrite are being called again and again. I know to remove code-duplication I have to make functions and pass arguments to them but I am not able to think of a way doing it. Can you post some example for me, out of this code:
3
5289
by: Allen Chen [MSFT] | last post by:
Hi Richard, Quote from Richard================================================== However I also want to be able to remove the panes. I have tried to include this, but find that when I first add the pane the remove event does not get handled, though thereafter it is handled without problems. ==================================================
0
9997
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10971
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10494
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9666
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5887
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4720
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3317
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.