在上一个教程中,您学习了如何编写第一个 C 程序。现在,让我们来学习 C 注释。
提示:我们在这本教程系列中较早介绍注释,因为从现在开始,我们将使用它们来解释我们的代码。
注释是我们添加到代码中的提示,使代码更易于理解。
C 编译器会完全忽略注释。
例如,
#include <stdio.h>
int main() {
// print Hello World to the screen
printf("Hello World");
return 0;
}
输出
Hello World
这里,// print Hello World to the screen
是 C 编程中的一个注释。C 编译器会忽略 //
符号之后的所有内容。
注意:您可以忽略编程概念,只关注注释。我们将在以后的教程中回顾这些概念。
C 中的单行注释
在 C 中,单行注释以 //
符号开头。它在同一行开始和结束。例如,
#include <stdio.h>
int main() {
// create integer variable
int age = 25;
// print the age variable
printf("Age: %d", age);
return 0;
}
输出
Age: 25
在上面的示例中,我们使用了两个单行注释
-
// 创建整型变量
// 打印 age 变量
我们也可以将单行注释与代码一起使用。
int age = 25; // create integer variable
在这里,//
之前的代码会被执行,//
之后的所有代码都会被编译器忽略。
C 中的多行注释
在 C 编程中,还有另一种类型的注释,它允许我们一次注释多行,这就是多行注释。
要编写多行注释,我们使用 /*....*/
符号。例如,
/* This program takes age input from the user
It stores it in the age variable
And, print the value using printf() */
#include <stdio.h>
int main() {
// create integer variable
int age = 25;
// print the age variable
printf("Age: %d", age);
return 0;
}
输出
Age: 25
在这种类型的注释中,C 编译器会忽略从 /*
到 */
的所有内容。
注意:请记住使用注释的键盘快捷键
- 单行注释:ctrl + / (Windows) 和 cmd + / (Mac)
- 多行注释:ctrl + shift + / (Windows) 和 cmd + shift + / (Mac)
使用注释阻止代码执行
在调试过程中,可能存在我们不想要代码的某些部分的情况。例如,
在下面的程序中,假设我们不需要与高度相关的数据。因此,与其删除与高度相关的代码,不如将其注释掉。
#include <stdio.h>
int main() {
int number1 = 10;
int number2 = 15;
int sum = number1 + number2;
printf("The sum is: %d\n", sum);
printf("The product is: %d\n", product);
return 0;
}
这里,由于我们没有定义 product 变量,代码会报错。
我们可以注释掉导致错误的那个代码。
例如,
#include <stdio.h>
int main() {
int number1 = 10;
int number2 = 15;
int sum = number1 + number2;
printf("The sum is: %d\n", sum);
// printf("The product is: %d\n", product);
return 0;
}
现在,代码可以正常运行,没有错误。
在这里,我们通过注释掉与产品相关的代码解决了错误。
如果我们将来需要计算产品,可以取消注释。
为什么使用注释?
我们应该出于以下原因使用注释:
- 注释使我们的代码更具可读性,便于将来参考。
- 注释用于调试目的。
- 我们可以使用注释进行代码协作,因为它可以帮助其他开发人员理解我们的代码。
注意:注释不是也不应该被用作解释写得不好的代码的替代品。总是努力编写清晰、易于理解的代码,然后将注释作为补充。
在大多数情况下,总是使用注释来解释“为什么”而不是“怎么做”,这样就足够了。
接下来,我们将详细学习 C 变量、常量和字面量。