- 注册时间
- 2011-3-6
- 最后登录
- 1970-1-1
该用户从未签到
|
<ul class="text" style="margin:0px; padding:0px; list-style:none; font-size:14px; word-wrap:break-word; color:rgb(63,62,60); font-family:'Hiragino Sans GB',微软雅黑,黑体,Arial,sans-serif">
1.变量定义 每行一个
2.一行代码只做一件事
3.if、for、while、do等语句自占一行,执行语句不得紧跟其后。不论执行语句有多少都要加{}。这样可以防止书写失误。
4.循环后应空一行 在写其他代码
5.尽可能在定义变量的同时初始化该变量(就近原则)
6.函数参数,后应+一个空格
void Func1(int x, int y, int z); // 良好的风格
void Func1 (int x,int y,int z); // 不良的风格[/code]
7.if for while 等 后应+一个空格
if (year >= 2000) // 良好的风格
if(year>=2000) // 不良的风格
if ((a>=b) && (c<=d)) // 良好的风格
if(a>=b&&c<=d) // 不良的风格[/code]
8.三木运算符都应该加一个空格
x = a < b ? a : b; // 良好的风格
x=a<b?a:b; // 不好的风格
[/code]
9.{}应该对齐 我是不太喜欢
10.长行拆分
if ((very_longer_variable1 >= very_longer_variable12)
&& (very_longer_variable3 <= very_longer_variable14)
&& (very_longer_variable5 <= very_longer_variable16))
{
dosomething();
}
virtual CMatrix CMultiplyMatrix (CMatrix leftMatrix,
CMatrix rightMatrix);
for (very_longer_initialization;
very_longer_condition;
very_longer_update)
{
dosomething();
}
[/code]
11.注释 对函数的注释
/*
* 函数介绍:
* 输入参数:
* 输出参数:
* 返回值 :
*/
void Function(float x, float y, float z)
{
…
}
[/code]
多种嵌套的时候应在段落结束处加注释便于阅读
if (…)
{
…
while (…)
{
…
} // end of while
…
} // end [/code]
12.变量的名字应当使用“名词”或者“形容词+名词”。
例如:
float value;
float oldValue;
float newValue;
[/code]
13.全局函数的名字应当使用“动词”或者“动词+名词”(动宾词组)。类的成员函数应当只使用“动词”,被省略掉的名词就是对象本身。
例如:
DrawBox(); // 全局函数
box->Draw(); // 类的成员函数
[/code]
14.用正确的反义词组命名具有互斥意义的变量或相反动作的函数等。
例如:
int minValue;
int maxValue;
int SetValue(…);
int GetValue(…);
[/code]
15.避免出现Value1 ,Value2 编号名称
16.变量和参数应用小写字母开头的单词组合而成
17.常量全用大写字母 用下划线分割单词
最好使用const
const int MAX = 100;
const int MAX_LENGTH = 100;[/code]
18.静态变量加前缀s_(表示static)
19.全局变量前缀g_()表示global)
20.位运算中最好使用括号
例如:
word = (high << 8) | low
if ((a | b) && (a & c)) [/code]
21.BOOL值最好不要直接跟1 0 TRUE FALSE比较
直接使用
BOOL flag;
if (flag) or if (!flag)[/code]
22.整数不应该模仿BOOL比较 应直接与0比较
23.指针最好跟NULL比较
比较是最好是NULL在前
如:
if (NULL != p)[/code]24.if的补充说明
程序中有时会遇到if/else/return的组合,应该将如下不良风格的程序
if (condition)
return x;
return y;
[/code]
改写为
if (condition)
{
return x;
}
else
{
<span style="white-space:pre"> </span>return y;
<span style="white-space:pre"> </span>}[/code]
或者改写成更加简练的
return (condition ? x : y);[/code]
25.使用多重循环时 应将循环少的放置外层
如
低效率:
for (row=0; row<100; row++)
{
for ( col=0; col<5; col++ )
{
sum = sum + a[row][col];
}
}
[/code]
高效率:
for (col=0; col<5; col++ )
{
for (row=0; row<100; row++)
{
sum = sum + a[row][col];
}
}
[/code]
26.要简洁 or 效率?
for (i=0; i<N; i++)
{
if (condition)
DoSomething();
else
DoOtherthing();
}
if (condition)
{
for (i=0; i<N; i++)
DoSomething();
}
else
{
for (i=0; i<N; i++)
DoOtherthing();
}
[/code]
建议还是简洁
27.switch 不要忘了在case后加break 和最后default : break
28.尽量不使用goto 我要XX这边 goto直接还是很好用的
跳出循环 控制台程序跳置开头重新执行
post 32 of 101
2016年3月22日1:21:24 |
|