Chinaunix首页 | 论坛 | 博客
  • 博客访问: 642185
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: LINUX

2011-04-07 16:35:48

http://www.cnblogs.com/wwang/archive/2011/02/24/1960283.html
缩进

1、除了注释、文档和Kconfig之外,使用Tab缩进,而不是空格,并且Tab的宽度为8个字符;

2、switch ... case ...语句中,switch和case具有相同的缩进(参考上文);

花括号

3、花括号的使用参考K&R风格。

如果是函数,左花括号另起一行:

1int function(int x)
2{
3        body of function
4}

否则,花括号紧接在语句的最后:

1if (x is true) {
2        we do y
3}

如果只有一行语句,则不需要用花括号:

1if (condition)
2        action();

但是,对于条件语句来说,如果一个分支是一行语句,另一个分支是多行,则需要保持一致,使用花括号:

1if (condition) {
2        do_this();
3        do_that();
4} else {
5        otherwise();
6}
空格

4、在关键字“if, switch, case, for, do, while”之后需要加上空格,如:

1if (something)

5、在关键字“sizeof, typeof, alignof, or __attribute__”之后不要加空格,如:

1sizeof(struct file)

6、在括号里的表达式两边不要加空格,比如,下面是一个反面的例子

1sizeof( struct file )

7、大多说的二元和三元运算符两边需要空格,如“= + - < > * / % | & ^ <= >= == != ? :”;

8、一元运算符后面不要空格,如“& * + - ~ ! sizeof typeof alignof __attribute__ defined”;

9、在前缀自增自减运算符之后和后缀自增自减运算符之前不需要空格(“++”和“--”);

10、结构成员运算符(“.”和“->”)的两边不需要空格;

11、行尾不需要空格;

注释

12、使用C89的“/* ... */”风格而不是C99的“// ...”风格;

13、对于多行注释,可以参考下例:

1/*
2* This is the preferred style for multi-line
3* comments in the Linux kernel source code.
4* Please use it consistently.
5*
6* Description: A column of asterisks on the left side,
7* with beginning and ending almost-blank lines.
8*/
Kconfig

14、“config”定义下面的语句用Tab缩进,help下面的语句再额外缩进两个空格,如:

1config AUDIT
2        bool "Auditing support"
3        depends on NET
4        help
5          Enable auditing infrastructure that can be used with another
6          kernel subsystem, such as SELinux (which requires this for
7          logging of avc messages output). Does not do system-call
8          auditing without CONFIG_AUDITSYSCALL.

15、多行的宏定义需要用“do .. while”封装,如:

1#define macrofun(a, b, c)               \
2do {                                    \
3        if (a == 5)                     \
4                do_this(b, c);          \
5} while (0)
函数返回值

16、函数返回值的定义最好也要遵循一定的章法。

如果函数的名称是一种动作或者命令式的语句,应该以错误代码的形式返回(通常是0表示成功,-Exxx这种形式的负数表示错误),如:

1do_something()

如果函数的名称是判断语句,则返回值应该类似与布尔值(通常1表示成功,0表示错误),如:

1something_is_present()
阅读(1378) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~