吕慧伟

吕慧伟的博客

他的个人主页  他的博客

K&R和GNU代码风格

吕慧伟  2009年10月29日 星期四 13:49 | 6633次浏览 | 11条评论

使用indent工具来得到规范的代码。

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

评论

我的评论:

发表评论

请 登录 后发表评论。还没有在Zeuux哲思注册吗?现在 注册 !
李洋

回复 李洋  2009年10月30日 星期五 12:46

印象中AStyle是可以选择几种风格的代码格式,好像有这两种

3条回复

Will Song

回复 Will Song  2009年10月30日 星期五 12:12

习惯{单列一行,对得齐,看的清楚。。。

2条回复

刘磊(V.L.)

回复 刘磊(V.L.)  2009年10月29日 星期四 18:54

k&r缩进好像是一个tab

1条回复

王依依

回复 王依依  2009年10月29日 星期四 18:03

比较喜欢 k&r 省行

1条回复

暂时没有评论

Zeuux © 2024

京ICP备05028076号