星期三, 十月 28, 2009

[Coding]代码风格

K&R

缩进为4格,{跟在控制语句后面
int foo(int k)
{
    if (k < 0 || k > 2) {
        printf("out of range\n");
        printf("this function requires a value of 1 or 2\n");
    } else {
        printf("Switching\n");
        switch (k) {
        case 1:
            printf("1\n");
            break;
        case 2:
            printf("2\n");
            break;
        }
    }
}
使用K&R
$ indent -kr *.c *.h
在.vimrc中添加
function! KRIndent()
        set shiftwidth=4
endfunction
au FileType c,cpp,h,hh call KRIndent()

GNU

函数类型定义另起一行。缩进为2格。{另起一行。
int
foo (int k)
{
if (k < 0 || k > 2)
{
printf ("out of range\n");
printf ("this function requires a value of 1 or 2\n");
}
else
{
printf ("Switching\n");
switch (k)
{
case 1:
printf ("1\n");
break;
case 2:
printf ("2\n");
break;
}
}
}
使用GNU
$ indent *.c *.h
在.vimrc中添加
function! GnuIndent()
        setlocal cinoptions=>4,n-2,{2,^-2,:2,=2,g0,h2,p5,t0,+2,(0,u0,w1,m1
        setlocal shiftwidth=2
        setlocal tabstop=8
endfunction
au FileType c,cpp,h,hh call GnuIndent()
其他,还有Linux/BSD等等。有兴趣的话可以参考Reference

Reference
http://en.wikipedia.org/wiki/Prettyprint
http://en.wikipedia.org/wiki/Indent_style
http://www.gnu.org/software/indent/manual/indent.html

没有评论: