C/C++ 中不允许嵌套注释。但是,当您尝试将一对评论放入另一对时,以下错误意味着什么?
Nesting comments is not allowed in C/C++. But what do the following errors mean when you try to put one comment pair inside the other?
考虑 Lippman 'C++ Primer' 中的以下代码,
#include <iostream>
/*
* comment pairs /* */ cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/
int main(){
return 0;
}
编译时,
$cl -EHsc .\Program.cc
Microsoft (R) C/C++ Optimizing Compiler Version 19.30.30706 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
Program.cc
.\Program.cc(4): error C4430: missing type specifier - int assumed. Note: C++ does not
support default-int
.\Program.cc(4): error C2146: syntax error: missing ';' before identifier 'nest'
.\Program.cc(7): warning C4138: '*/' found outside of comment
.\Program.cc(10): error C2143: syntax error: missing ';' before '{'
.\Program.cc(10): error C2447: '{': missing function header (old-style formal list?)
问题 1:从书中提到的代码中,““不能嵌套”被认为是源代码,程序的其余部分也是如此”是什么意思?
问题 2:嵌套评论时会发生什么?均值产生的这些相当混乱的错误是什么意思?
评论以 /*
开始,以 */
结束。所以在例子中,注释是
/*
* comment pairs /* */
评论中有第二个 /*
的事实并没有“重启”它。它仍然以 */
.
结束
因此,编译器会尝试将 cannot nest.
解释为源代码。它最好的猜测似乎是 int cannot
可能是一个变量声明,但缺少 int
。然后nest
也有点不对,一直报错...
只有第一次出现的序列 */
结束注释块。之前放置了多少次 /*
并不重要(任何后续的 /*
都是注释的一部分,而不是打开新块)。错误取决于您在代码中的内容,并且可能很难发现。在您的情况下,它会找到未注释的标记 cannot
,这在该上下文中无效。
您的代码等同于:
#include <iostream>
cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/
int main() {
return 0;
}
这完全是垃圾,因此编译器会输出相应的错误消息。
考虑 Lippman 'C++ Primer' 中的以下代码,
#include <iostream>
/*
* comment pairs /* */ cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/
int main(){
return 0;
}
编译时,
$cl -EHsc .\Program.cc
Microsoft (R) C/C++ Optimizing Compiler Version 19.30.30706 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
Program.cc
.\Program.cc(4): error C4430: missing type specifier - int assumed. Note: C++ does not
support default-int
.\Program.cc(4): error C2146: syntax error: missing ';' before identifier 'nest'
.\Program.cc(7): warning C4138: '*/' found outside of comment
.\Program.cc(10): error C2143: syntax error: missing ';' before '{'
.\Program.cc(10): error C2447: '{': missing function header (old-style formal list?)
问题 1:从书中提到的代码中,““不能嵌套”被认为是源代码,程序的其余部分也是如此”是什么意思?
问题 2:嵌套评论时会发生什么?均值产生的这些相当混乱的错误是什么意思?
评论以 /*
开始,以 */
结束。所以在例子中,注释是
/*
* comment pairs /* */
评论中有第二个 /*
的事实并没有“重启”它。它仍然以 */
.
因此,编译器会尝试将 cannot nest.
解释为源代码。它最好的猜测似乎是 int cannot
可能是一个变量声明,但缺少 int
。然后nest
也有点不对,一直报错...
只有第一次出现的序列 */
结束注释块。之前放置了多少次 /*
并不重要(任何后续的 /*
都是注释的一部分,而不是打开新块)。错误取决于您在代码中的内容,并且可能很难发现。在您的情况下,它会找到未注释的标记 cannot
,这在该上下文中无效。
您的代码等同于:
#include <iostream>
cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/
int main() {
return 0;
}
这完全是垃圾,因此编译器会输出相应的错误消息。