C语言代码风格指北

没有考虑清楚就开始无脑写代码就是耍流氓!

好的文档

好的代码应当是自注释的。变量名、函数调用应当表明了代码干了什么事。注释应当用于解释why的问题。代码中的以下组件值得注释

  • 文件头: Each file should contain a comment describing the purpose of the file and how it fits in to the larger project. This is also a good place to put your name and email address.
  • 函数头: Each function should be prefaced with a comment describing the purpose of the function (in a sentence or two), the function’s arguments and return value, any error cases that are relevant to the caller, any pertinent side effects, and any assumptions that the function makes.
  • 大的代码块: If a block of code is particularly long, a comment at the top can help the reader know what to expect as they’re reading it, and let them skip it if it’s not relevant.
  • 深奥的代码: If there’s no way to make a bit of code self-evident, then it is acceptable to describe what it does with a comment. In particular, pointer arithmetic is something that often deserves a clarifying comment.

关于function header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * @brief <大写开头,完整的一句话,有结尾标点>
 *
 * <这里的内容不会显示在函数指引中>
 * <What does this function do?>
 * <What are the function's arguments?>
 * <What is the function's return value?>
 * <Are there any preconditions or postconditions>
 * 
 *  * "Each function should be prefaced with a comment describing the purpose
 *  of the function (in a sentence or two), the function's arguments and
 *  return value, any error cases that are relevant to the caller,
 *  any pertinent side effects, and any assumptions that the function makes."
 *
 * @param
 * @return
 * @pre
 * @post
 */
  • 对函数意图的注释
  • 函数参数
  • 函数返回值
  • 和调用者相关的错误情况
  • 任何有关的副作用
  • 函数所做的任何预期

关于宏和const

  • const
    • 对于常量,请使用const
    • 避免魔数,请使用const常量
    • 仅在需要区分debug模式的情况下,使用相关宏
    • 小技巧: 非debug情况下,可以使用sizeof避免编译器报错”unused varaible”,如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifdef DEBUG
/* When DEBUG is defined, these form aliases to useful functions */
#define dbg_printf(...) printf(__VA_ARGS__)
#define dbg_requires(expr) assert(expr)
#define dbg_assert(expr) assert(expr)
#define dbg_ensures(expr) assert(expr
#else
/* When DEBUG is not defined, no code gets generated for these */
/* The sizeof() hack is used to avoid "unused variable" warnings *
#define dbg_printf(...) (sizeof(__VA_ARGS__), -1)
#define dbg_requires(expr) (sizeof(expr), 1)
#define dbg_assert(expr) (sizeof(expr), 1)
#define dbg_ensures(expr) (sizeof(expr), 1
#endif

关于一行的长度

一行代码的长度应当小于80个字符。

为什么是80个字符呢?

  • 所有个人计算机上的显卡在加电自检后都会把自己初始化到80x25的文本模式,该模式下,屏幕上可以显示25行,每行80个字符,总共2000个字符。

格式化代码

可以使用clang-format格式化代码。

参考