在 C语言中,注释是程序中的一种特殊语句,用于向程序的读者解释代码的作用和用途。注释是程序员编写代码时的重要工具,可以提高代码的可读性和可维护性。
注释不会被编译器编译,也不会被计算机执行,仅仅是用来帮助程序员理解代码。在编写代码时,注释可以用来记录程序的设计思路、功能、参数、返回值等信息,也可以用来标记代码的不同部分,方便程序员快速定位和修改问题。
1 注释种类
1.1 单行注释
-
语法:// 待注释的内容
-
位置:可放在代码后,称之为行尾注释; 也可放代码上一行,称作行上注释。
-
作用:解释代码的功能、变量的含义、代码的作者、修改历史等信息。
#include <stdio.h>
int main(void)
{
// 输出hello, world
printf("Hello, world!\n");
return 0;
}
1.2 多行注释
-
语法:/* 待注释的内容 */
-
注意:多⾏注释内,可以嵌套单⾏注释。 多⾏注释之间不能嵌套。
-
作用:解释代码的算法、数据结构、程序流程等信息。
#include <stdio.h>
/*
* 程序入口
* @param 无
* @return 1 -- 函数执行成功
*/
int main(void)
{
printf("Hello, world!\n");
return 0;
}
2 注意事项
在编写注释时,需要注意以下几点:
-
注释应简洁明了,不要过多地描述无关内容。注释应该让程序员快速地理解代码的意图和设计,而不是让他们花费过多的时间来理解注释本身;
-
注释应与代码保持一致,避免出现注释与代码不一致的情况。如果代码有变更,注释也需要相应地进行修改;
-
注释应具有可读性,避免使用难以理解的术语或缩写。注释应该清晰地传达信息,而不是增加代码的复杂度;
-
注释应该放在合适的位置,让程序员容易地找到并理解注释的含义。注释应该放在需要解释的代码附近,而不是放在代码的任意位置;
-
注释应该是有用的,避免写无用的注释。注释应该提供有用的信息,帮助程序员理解代码和设计意图。
3 注释范例
3.1 文件头注释
/*
* misc.c
*
* This is a collection of several routines from gzip-1.0.3
* adapted for Linux.
*
* malloc by Hannu Savolainen 1993 and Matthias Urlichs 1994
*
* Modified for ARM Linux by Russell King
*
* Nicolas Pitre <nico@visuaide.com> 1999/04/14 :
* For this code to run directly from Flash, all constant variables must
* be marked with 'const' and all other variables initialized at run-time
* only. This way all non constant variables will end up in the bss segment,
* which should point to addresses in RAM and cleared to 0 on start.
* This allows for a much quicker boot time.
*/
3.2 函数关键注释
static int num_rounds(struct crypto_aes_ctx *ctx)
{
/*
* # of rounds specified by AES:
* 128 bit key 10 rounds
* 192 bit key 12 rounds
* 256 bit key 14 rounds
* => n byte key => 6 + (n/4) rounds
*/
return 6 + ctx->key_length / 4;
}