代码风格(一)注释、头文件、宏定义

做程序员已经两年多了,感觉代码风格很重要,所以决定抽点时间定制一下自己的代码风格。

参考文档:http://learn.akae.cn/media/ch09.html

代码风格的重要性:

1、 代码风格是一个规范,编写代码的时候就有了规矩,有规矩应该是成熟的标志。

就像是一个人到了一定的年龄,做人处事的时候就有了自己原则一样。

2、 提高编程质量。优秀的代码规范可以使程序员与代码交流的时候,会发生共鸣。

3、 提高效率。因为有规范,编写代码之时自然对于代码的布局胸有成竹,不再犹豫。

4、 美观。爱美之心,人皆有之。

5、 此规范是针对自己的编程习惯和环境,请大家多提意见共勉之。

编程环境简介:

编程语言:Linux C

编辑器:vim

一、注释

1、文件注释--文件说明
/*
* The revision control tag appears first, with a blank line after it.
* Copyright text appears after the revision control tag.
*/


2、单行注释
/* Most single-line comments look like this. */

3、多行注释
/*
* Multi-line comments look like this. Make them real sentences. Fill
* them so they look like real paragraphs.
*/


二、头文件

1、重复包含保护
#ifndef _SYS_SOCKET_H_
#define _SYS_SOCKET_H_
/*
* Contents of #include file go between the #ifndef and the #endif at the end.
*/
#endif /* !_SYS_SOCKET_H_ */

2、头文件分类,头文件类之间隔一个空行

系统头文件先行,系统头文件也可分类,依据个人习惯。同一类的头文件依据首字母排序。
#include <sys/types.h> /* Non-local includes in brackets. */


#include <net/if.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <netinet/in.h>
#include <protocols/rwhod.h>


#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>


#include <paths.h>

#include "pathnames.h" /* Local includes in double quotes. */


三、main函数
main()函数应该在所出现文件的顶部,所用到的同模块函数可做如下声明。


static char *function(int, int, float, int);
static int dirinfo(const char *, struct stat *, struct dirent *,
struct statfs *, int *, char **[]);
static void usage(void);


int main(int, char *[]);


四、宏定义

宏名称必须大写。

1、多行宏定义格式
#define MACRO(v, w, x, y)\
do {\
v = (x) + (y); \
w = (y) + 2; \
} while (/* CONSTCOND */ 0)

2、单行宏定义格式
#define DOUBLE(x) ((x) * 2)

五、枚举变量定义格式
enum enumtype {
ONE,
TWO
} et;

六、结构体定义

1、遵循对其原则,节省空间

2、变量名具有提示作用
struct foo {
struct foo *next; /* List of active foo */
struct mumble amumble; /* Comment for mumble */
int bar;
unsigned int baz:1, /* Bitfield; line up entries if desired */
fuz:5,
zap:2;
uint8_t flag;
};
struct foo *foohead; /* Head of global foo list */

七、typedef 结构提别名应该和结构体同名,且大写。
typedef struct BAR {
int level;
} BAR;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值