if (condition) { // no spaces inside parentheses
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
}
如果你倾向于在圆括号内部加空格:
if ( condition ) { // spaces inside parentheses - rare
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
}
注意所有情况下if和左圆括号间有个空格,右圆括号和左大括号(如果使用的话)间也要有个空格:
if(condition) // Bad - space missing after IF.
if (condition){ // Bad - space missing before {.
if(condition){ // Doubly bad.
if (condition) { // Good - proper space after IF and before {.
有些条件语句写在同一行以增强可读性,只有当语句简单并且没有使用else子句时使用:
if (x == kFoo) return new Foo();
if (x == kBar) return new Bar();
如果语句有else分支是不允许的:
// Not allowed - IF statement on one line when there is an ELSE clause
if (x) DoThis();
else DoThat();
通常,单行语句不需要使用大括号,如果你喜欢也无可厚非,也有人要求if必须使用大括号:
if (condition)
DoSomething(); // 2 space indent.
if (condition) {
DoSomething(); // 2 space indent.
}
但如果语句中哪一分支使用了大括号的话,其他部分也必须使用:
// Not allowed - curly on IF but not ELSE
if (condition) {
} else
// Not allowed - curly on ELSE but not IF
if (condition)
else {
// Curly braces around both IF and ELSE required because
// one of the clauses used braces.
if (condition) {
} else {
}
switch (var) {
case 0: { // 2 space indent
... // 4 space indent
break;
case 1: {
break;
default: {
assert(false);
}
4 switch选择语句案例分享
最近似乎没看到特别的switch,暂且不写。
5 循环语句
单句声明的循环体中,括号是可选的。
for (int i = 0; i < kSomeNumber; ++i)
printf("I love you\n");
for (int i = 0; i < kSomeNumber; ++i) {
printf("I take it back\n");
}
空循环,要用括号或者continue,而不能直接用个分号。
while (condition) {
// Repeat test until it returns false.
for (int i = 0; i < kSomeNumber; ++i) {} // Good - empty body.
while (condition) continue; // Good - continue indicates no logic.
while (condition); // Bad - looks like part of do/while loop.
6 循环语句实际案例分享
for(i=0;i<length;i++)
SPICmd8bit(ptr[i]);
注意对比下,这里有好几个空格要加,实际完成效果如下。
for (i = 0; i < length; i++) {
SPICmd8bit(ptr[i]);
}