C++ 标准(源文件的换行符结尾)

C++ Standards (newline ending of source files)

我指的是:Why should text files end with a newline? 其中一个答案引用了 C89 标准。简而言之,文件必须以换行结尾,换行前不能紧跟反斜杠。

这是否适用于最新的 C++ 标准?

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World!" << endl;
  return 0;
}
//\

以上是否有效? (假设在//\之后有一个换行符,我一直无法显示)

给定的代码在 C++ 中是合法的,但在 C 中不合法。

的确,C (N1570) 标准说:

Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.

C++ 标准 (N3797) 对它的表述略有不同(强调我的):

Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. If, as a result, a character sequence that matches the syntax of a universal-character-name is produced, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.

根据 [lex.phases] p2 和 p3,您的特定情况在 c++ 标准中也是格式错误的。 [lex.phases] p2 说

Each sequence of a backslash character () immediately followed by zero or more whitespace characters other than new-line followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. Except for splices reverted in a raw string literal, if a splice results in a character sequence that matches the syntax of a universal-character-name, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a splice, shall be processed as if an additional new-line character were appended to the file.

既然你说了

Assuming there is a newline after //, which I've been unable to display

因此,最后一个可见的 \ 符合拼接条件。因此,由 \ 组成的序列和换行符被删除。这意味着此源文件中的最后一个字符是 / 但后面没有换行符。 // 根据 [lex.comment] p1

开始评论

The characters // start a comment, which terminates immediately before the next new-line character.

根据 [lex.phases] p3

The source file is decomposed into preprocessing tokens ([lex.pptoken]) and sequences of whitespace characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment.

在您的例子中,字符 // 开始注释但没有新行来终止它。因此,这是一个部分评论。程序格式错误。