Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
According to cpp reference
C++-style comments tell the compiler to ignore all content between // and a new line.
So your comment should be legal. Notice that g++ is only giving a warning, not an error.
g++ is warning about the escaped newline
Warn whenever a comment-start sequence ‘/’ appears in a ‘/’ comment, or whenever a backslash-newline appears in a ‘//’ comment. This warning is enabled by -Wall
Such comments are legal, but they could have unexpected effects, hence the warning. The next line after the one with the backslash at the end is a continuation of the comment, regardless of the //
at the beginning. So this
// \\
Hey dude!
int main () {}
is a valid C++ program. And no, the backslash before the last one does not serve as an escape.
If you want to avoid the warning, put a LaTeX comment in the end of the line:
// y_1 &=& x_1 \\ % look ma, no warning
Note that a simple space between the backslash and the newline doesn't necessarily fix the problem. GCC documentation says:
If there is white space between a backslash and the end of a line, that is still a continued line. However, as this is usually the result of an editing mistake, and many compilers will not accept it as a continued line, GCC will warn you about it.
Is it legal? Yes. Is it error prone? Yes. That's why you are getting a warning.
The C/C++ standard has one token above all (processed first): \
This token removes the line break. Consider the following code:
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.
Despite stackoverflow's syntax highlighting, lines 2 and 5 are not compiled.
In case you're wondering, the next tokens are //
and /*
.
// /* incomplete block comment
int compiled_code = 0;
/*
// this entire line isn't commented */ int compiled_code_2 = 0;
which compiler is right?
Both, because warnings are irrelevant to the standard. They compiled successfully and that's all that matters - they both conformed properly to the standard.