简体   繁体   English

C++中打印到stdout时/*注释的行为

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

my question comes from the following 2 simple line of C++ code:我的问题来自以下 2 行简单的 C++ 代码:

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

In my opinion, the comment delimiters /* */ eat the characters "; and cout<<" which is inside of them.在我看来,注释分隔符/* */吃掉了其中的字符";cout<<" 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.代码是在 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. C 标准告诉我们如何运行解析器,结果证明(出于各种原因)当您开始解析字符串文字时,您不会停止直到到达双引号结尾,即使其中有注释字符中间。 Try some of these:尝试其中一些:

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

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

From the C FAQ .来自 C常见问题解答

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.字符序列 /* 和 */ 在双引号字符串中并不特殊,因此不会引入注释,因为程序(特别是生成 C 代码作为输出的程序)可能想要打印它们。 (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 "/*".) (很难想象为什么有人想要或需要在带引号的字符串中放置注释。很容易想象需要打印“/*”的程序。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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