C++,在多行代码段中注释

C++, comment in a multi-line piece of code

本文关键字:代码 段中 注释 C++      更新时间:2023-10-16

不应该代码:

int Func(int a, // comment
int b, // comment
int c  // comment
) ...

等效于:

int Func(int a, // comment int b, // comment int c  // comment) ...

为什么它可以正确构建(至少使用 G++(?

到目前为止,在这种情况下,我总是使用/* */评论。

int Func(int a, // comment
int b, // comment
int c  // comment
) ...

转换为

int Func(int a,  
int b,  
int c   
) ...

在翻译的第三阶段。 如果你想在翻译阶段发生之前单行等效,那么你需要使用类似/* */

int Func(int a /*comment 1*/, int b /*comment 2*/, int c /*comment 3*/ ) ...

从标准

5.7 注释

字符//开始评论,评论立即终止 在下一个换行符之前...

因此,在注释被剥离出来后,编译器最终解释的代码如下所示:

int Func(int a,
int b,
int c 
) {}

即使是换行符也将保持不变。

注释与代码无关,因此此代码:

int Func(int a, // comment
int b, // comment
int c  // comment
) {}

其实等价于这个:

int Func(int a,
int b,
int c 
) {}

或者如果你还想要这个:

int Func(int a,int b,int c) {}

单行注释以//结尾开头,因此将代码与注释放在同一行会将代码转换为注释,并且您的两个代码段并不等效。

有两种注释:

  • //开头的注释在行尾终止
  • /*开头的注释将在下一个*/终止

最初的 C 规范只知道/* */样式注释。

//样式注释是随C++引入的,后来也在 C 标准中引入(虽然不确定是哪一个(。

所以这个:

int Func(int a, // comment
int b, // comment
int c  // comment
) ...

相当于这个:

int Func(int a, /* comment */
int b, /* comment */
int c  /* comment */
) ...

相当于这个:

int Func(int a, /* comment */ int b, /* comment */ int c  /* comment */) ...