1、要养成边写代码边注释的习惯,程序员基本不会先写完代码再注释。代码不加注释,其他人很难读懂,即使是自己写的代码,没有注释自己再回头来读,也很费时。
2、代码加上注释便于后期维护。
3、注释可以增加代码的可读性。如下面的语句,可读性很差吧,但如果加上注释,即使没学过C,也知道这条语句的功能。
return((s1<s2) ? s1:s2);
return((s1<s2) ? s1:s2); /*Gets the smaller of 2 values */
4、不要对每行代码进行注释,实际上只需要注释少数几行。很多程序员喜欢在代码块的头部,注释多行,然后只在程序中间注释一两行。
例如:
/* The first code listing from Ch3 of The Absolute Beginner's Guide to C Teaching new programer to create kick-butt code */
/* A Dean Miller joint */
/* Filename chapter3ex.1.c */
/* Totals how much money will be spent on holiday gifts. */
#include<stdio.h>
main()
{
float gift1, gift2; /* Variables to hold costs. */
float total; /* Variable to hold total amount */
/* Asks for each gift amount */
printf("How much do you want to spend on your mon?");
scanf(" %f", &gift1);
printf("How much do you want to spend on your dad?");
scanf("%f", &gift2);
total = gift1 + gift2; /* Coumputes total amount spent on gifts */
printf("\nThe total you will be spending on gifts is $%0.2f\n", total);
return 0; /* Ends the program */
}
5、很多软件公司要求程序员在代码的头部加上名字,以便后期程序需要修改时能联系到代码的原编写者。最好把程序的文件名也列在程序的头部,这样方便在电脑中查找到源程序。