简体   繁体   中英

The behavior of /* comment when printing to stdout in C++

my question comes from the following 2 simple line of C++ code:

cout<<"/*";
cout<<"*/";

In my opinion, the comment delimiters /* */ eat the characters "; and cout<<" which is inside of them. So the two lines must be equal to:

cout<<"";

Surprisingly, when I compile and test the code, the program prints:

/**/

It is likely the program recognize comment delimiter as normal characters. How could that be? The code was compiled in gcc-c++-4.7.2.

The C standard tells us how to run the parser, and it turns out that (for various reasons) when you begin parsing a string literal, you don't stop until you reach the end double-quote, even if there's a comment character in the middle. Try some of these:

cout<<"// this won't give an error";

cout<<"Does it print /* this here */?";

From the C FAQ .

The character sequences /* and */ are not special within double-quoted strings, and do not therefore introduce comments, because a program (particularly one which is generating C code as output) might want to print them. (It is hard to imagine why anyone would want or need to place a comment inside a quoted string. It is easy to imagine a program needing to print "/*".)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM