出于文档目的,我需要在我的C ++注释中添加一些LaTeX方程,例如:
//
// \begin{eqnarray*}
// y_1 &=& x_1 \\
// y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
(还要注意,我不能使用C样式注释/ * ... * /,因为它们与我用来处理注释的文档工具不兼容)
使用clang ++(版本9.0.1-10),我可以毫无问题地编译代码:
clang++ -Wall prog.cpp
但使用g ++(9.2.1版)
g++ -Wall prog.cpp
我收到此警告:
prog.cpp:3:1: warning: multi-line comment [-Wcomment] 3 | // y_1 &=& x_1 \\ | ^
我的问题:哪个编译器正确?我可以在C ++ \\
注释中合法使用//
吗?
合法吗?是。它容易出错吗? 是这就是您收到警告的原因。
C / C ++标准首先具有一个令牌(首先处理):\
此令牌删除换行符。考虑以下代码:
1. // the below code is commented out \
2. despite not having a comment at the beginning of the line
3.
4. // it's important to be careful because \\
5. int not_compiled_code = 0;
6. // the above code is not compiled.
尽管stackoverflow语法突出显示,但第2和第5行未编译。
[如果您想知道,下一个标记是//
和/*
。
// /* incomplete block comment
int compiled_code = 0;
/*
// this entire line isn't commented */ int compiled_code_2 = 0;
哪个编译器是正确的?
两者,因为警告与标准无关。
C ++样式的注释告诉编译器忽略//和换行之间的所有内容。
因此您的评论应合法。请注意,g ++仅给出警告,而不是错误。
g++ is warning about the escaped newline
警告,当注释开始序列'/ '出现在'/'注释中,或者反斜杠换行符出现在'//'注释中时,都会发出警告。通过-Wall启用此警告
哪个编译器正确?
两者该警告不是关于“ \
的合法使用”,而是关于多行注释。
在行尾的\
字符表示忽略换行符。所以这两行:
// blabla\
abcabc
和:
// blabalabcbc
完全相同。双反斜杠\\
只是被\
转义的反斜杠\
,因此先用反斜杠代替,然后预处理器先检测反斜杠,然后再检测换行符并删除换行符。这就是为什么它很危险。
int a = 1;
// increase a \\
a++;
printf("%d\n", a); // will print `1`