每行至多包含一条语句,例如:
argv++; // 正确
argc--; // 正确
argv++; argc--; // 避免!
复合语句是包含在大括号中的语句序列,形如{ statements }。例如下面各段。
if-else 或 for控制结构的一部分。这样便于添加语句而无需担心由于忘了加括号而引入bug。一个带返回值的 return 语句不使用小括号"()",除非它们以某种方式使返回值更为显见。例如:
return;
return myDisk.size();
return (size ? size : defaultSize);
if-else语句应该是以下形式:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
注意: if语句通常使用{}。避免下面容易出错的形式:
if (condition) // 避免!这省略了括号{ }!
statement;
for 语句应该是如下形式:
for (initialization; condition; update) {
statements;
}
空的for语句 (所有工作都在初始化,条件判断,更新子句中完成) 应该是如下形式:
for (initialization; condition; update);
当在for语句的初始化或更新子句中使用逗号时,避免因使用三个以上变量,而导致复杂度提高。若需要,可以在for循环之前(为初始化子句)或for循环末尾(为更新子句)使用单独的语句。
while 语句应该是如下形式:
while (condition) {
statements;
}
空的 while 语句应该是如下形式:
while (condition);
do-while 语句应该是如下形式:
do {
statements;
} while (condition);
switch 语句应该是如下形式:
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
每当一个 case 顺着往下执行时(因为没有 break 语句),通常应在 break 语句的位置添加注释。上面的示例代码中就包含注释 /* falls through */。
Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.
try-catch 语句应该是如下格式:
try {
statements;
} catch (ExceptionClass e) {
statements;
}
一个try-catch语句后面也可能跟着一个finally语句,不论try代码块是否顺利执行完,它都会被执行。
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}