命名、缩进、动态分配和释放内存、输入参数检查、错误处理、异常检查、注释等。
缩进:
a = b; // 等号两边有空格
if (a >= b){ // 条件判断括号前面有空格
printf("...\n");
}
else{
...
}
for (int i = 0; i < n; i++){ // 循环语句括号前有空格;冒号后面有空格
...
}
动态分配和释放内存:
#include <stdio.h> #include <stdlib.h> ... ... char *szFileBuffer = NULL; szFileBuffer = (char*)malloc(sizeof(char) * BUFFER_SIZE); memset(szFileBuffer, 0, BUFFER_SIZE); if (NULL == szFileBuffer){ perror("Allocate szFileBuffer Error!\n"); exit(1); // 异常退出,返回1给操作系统 } ...... free(szFileBuffer);
输入参数检查:
int fun(IN HANDLE hFile, IN OUT char *szFileBuffer){ if (NULL == hFile && NULL == szFileBuffer){ perror("Input Error in fun!\n"); return 0; // 可使用exit(1)异常退出;大型软件应用返回值判断是否继续运行程序,或进行异常处理 } }
错误处理:
char *s = malloc(sizeof(char) * 100);
if (!s){
printf("s allocate memory error!\n");
exit(0);
}
其他细节:
#ifndef FUN_H
#define FUN_H
......
#endif