LK’s CodingStyle Notes(1-3)
在参看Linux的CodingStyle(位于Linux内核的Documentation\CodingStyle文件)的过程中,这是一个非常完美的编码规范.
小小笔记一下。
Chapter 1: Indentation 排版
1) 对于Tab占位的大小问题有很多的纷争,有些人趋向于8个空格等于1个tab,有些人则喜欢使用4个空格(我就是如此)。不过不管那种排版方式,都是为了让代码更加清晰而设定的。
例如:
switch (suffix) {
case ‘G’:
case ‘g’:
mem <<= 30;
break;
case ‘M’:
case ‘m’:
mem <<= 20;
break;
case ‘K’:
case ‘k’:
mem <<= 10;
/* fall through */
default:
break;
}
关于这个,可以根据习惯而指定。
不要把多个语句放到同一行,就像:
if (condition) do_this;
do_something_everytime;
虽然对于比较短的语句来说这很方便,不过对于内核这种异常简洁的风格不要使用这种狡猾的技巧( Kernel coding style is super simple. Avoid tricky expressions.),因为这对于代码没有优化,还对阅读产生了一定的影响。
作为一个得体的编码人员,在每个语句后面都得留下空行,方便分段的阅读。
=================================================================
Chapter 2: Breaking long lines and strings 每行避免显得太长
编码样式都非常具有可读性的,所以要避免每行的字符太长,在此设定每行不能超过80个字符。
就像这样:
void fun(int a, int b, int c)
{
if (condition)
printk(KERN_WARNING "Warning this is a long printk with "
"3 parameters a: %u b: %u "
"c: %u \n", a, b, c);
else
next_statement;
}
"The limit on the length of lines is 80 columns and this is a hard limit."
=================================================================
Chapter 3: Placing Braces and Spaces 括号和空格的摆放
C风格的另一个问题是对于括号摆放位置的问题。不像上面所说的排版大小,这些括号都是由于一些技术原因而去选择摆放策略的。但最完美的选择,已经由先知Kernighan和Ritchie展示给大伙儿了,就是在开头和结尾放上大括号!
if (x is true) {
we do y
}
这是给非函式语句块的格式。
还有:
switch (action) {
case KOBJ_ADD:
return "add";
case KOBJ_REMOVE:
return "remove";
case KOBJ_CHANGE:
return "change";
default:
return NULL;
}
而对于函式语句对于大括号的摆放是这样的:
int function(int x)
{
body of function
}
注意到没?这就简单完美的区分了语句块的使用方式了!
同事哦,这种大括号的放置方式,有效的避免了一个大括号独占一行的愚蠢举动,影响可读性,造成不必要的麻烦,think 25-line terminal screens here…
单语句不需要大括号,例如这样。
if (condition)
action();
但是需要换行。这并不与前面的话有冲突,让我们再想想只有25行的终端界面吧…
如果语句超过两行,就需要大括号了。
if (condition) {
do_this();
do_that();
} else {
otherwise();
}
对于空格,Linux内核样式相信函数关键字一一对应(function-versus-keyword)的法则,在关键字(大多数吧)的后面加上空格。
值得注意的是这里有一些关键字例外:sizeof, typeof, alignof, and __attribute__。
使用一个空格的关键字例如:if, switch, case, for, do, while
就像这样
if (condition) {
do_this();
do_that();
}
而为什么有些关键字不要空格.. s = sizeof(struct file); 因为加上空格后,
显得有些别扭( s = sizeof (struct file); )…
需要两边加上空格的还有: = + - < > * / % | & ^ <= >= == != ? :
而如作一元操作符不需要:
& * + - ~ ! sizeof typeof alignof __attribute__ defined ++ —
‘.’ and "->" 后的成员函数也是不需要空格的。
mrzenix post at 2008-7-24
Tags: codingstyle, Linux-kernel, World