C++ 注释是程序员可以添加的提示,以使他们的代码更易于阅读和理解。 它们被 C++ 编译器完全忽略。
有两种向代码中添加注释的方法:
// - 单行注释
/* */ - 多行注释
在 C++ 中,以//开头的任何行都是注释。 例如,
// declaring a variable
int a;
// initializing the variable 'a' with the value 2
a = 2; 在这里,我们使用了两个单行注释:
// declaring a variable// initializing the variable 'a' with the value 2
我们也可以这样使用单行注释:
int a; // declaring a variable在 C++ 中,/*和*/之间的任何行也是注释。 例如,
/* declaring a variable
to store salary to employees
*/
int salary = 2000; 此语法可用于编写单行和多行注释。
注释也可以用于禁用代码以阻止其执行。 例如,
#include <iostream>
using namespace std;
int main() {
cout << "some code";
cout << ''error code;
cout << "some other code";
return 0;
} 如果我们在运行程序时遇到错误,则可以删除注释,而不必删除容易出错的代码,而是可以使用注释使它无法执行。 这可能是有价值的调试工具。
#include <iostream>
using namespace std;
int main() {
cout << "some code";
// cout << ''error code;
cout << "some other code";
return 0;
} 专业提示:记住使用注释的快捷方式; 这真的很有帮助。 对于大多数代码编辑器,对于 Windows 是Ctrl + /,对于 Mac 是Cmd + /。
如果我们在代码上写注释,那么以后我们将更容易理解代码。 而且,您的其他开发人员将更容易理解代码。
注意:注释不能替代解释英文书写不好的代码的方法。 我们应该始终编写结构合理且易于解释的代码。 然后,使用注释。
作为一般经验法则,请使用注释来解释为什么做某事,而不是您如何做某事,并且您很好。