代碼風格和格式確實比較隨意, 但一個項目中所有人遵循同一風格是非常容易的. 個體未必同意下述每一處格式規(guī)則, 但整個項目服從統(tǒng)一的編程風格是很重要的, 只有這樣才能讓所有人能很輕松的閱讀和理解代碼.
另外, 我們寫了一個 emacs 配置文件 [http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el] 來幫助你正確的格式化代碼.
Tip
每一行代碼字符數(shù)不超過 80.
我們也認識到這條規(guī)則是有爭議的, 但很多已有代碼都已經(jīng)遵照這一規(guī)則, 我們感覺一致性更重要.
優(yōu)點:提倡該原則的人主張強迫他們調(diào)整編輯器窗口大小很野蠻. 很多人同時并排開幾個代碼窗口, 根本沒有多余空間拉伸窗口. 大家都把窗口最大尺寸加以限定, 并且 80 列寬是傳統(tǒng)標準. 為什么要改變呢?缺點:反對該原則的人則認為更寬的代碼行更易閱讀. 80 列的限制是上個世紀 60 年代的大型機的古板缺陷; 現(xiàn)代設備具有更寬的顯示屏, 很輕松的可以顯示更多代碼.結(jié)論:
80 個字符是最大值.
特例:
#include
語句可以超出80列. 但應該盡量避免.Tip
盡量不使用非 ASCII 字符, 使用時必須使用 UTF-8 編碼.
即使是英文, 也不應將用戶界面的文本硬編碼到源代碼中, 因此非 ASCII 字符要少用. 特殊情況下可以適當包含此類字符. 如, 代碼分析外部數(shù)據(jù)文件時, 可以適當硬編碼數(shù)據(jù)文件中作為分隔符的非 ASCII 字符串; 更常見的是 (不需要本地化的) 單元測試代碼可能包含非 ASCII 字符串. 此類情況下, 應使用 UTF-8 編碼, 因為很多工具都可以理解和處理 UTF-8 編碼. 十六進制編碼也可以, 能增強可讀性的情況下尤其鼓勵 —— 比如 "\xEF\xBB\xBF"
在 Unicode 中是 零寬度 無間斷 的間隔符號, 如果不用十六進制直接放在 UTF-8 格式的源文件中, 是看不到的. (yospaly 注: "\xEF\xBB\xBF"
通常用作 UTF-8 with BOM 編碼標記)
Tip
只使用空格, 每次縮進 2 個空格.
我們使用空格縮進. 不要在代碼中使用制符表. 你應該設置編輯器將制符表轉(zhuǎn)為空格.
Tip
返回類型和函數(shù)名在同一行, 參數(shù)也盡量放在同一行.
函數(shù)看上去像這樣:
ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
DoSomething();
...
}
如果同一行文本太多, 放不下所有參數(shù):
ReturnType ClassName::ReallyLongFunctionName(Type par_name1,
Type par_name2,
Type par_name3) {
DoSomething();
...
}
甚至連第一個參數(shù)都放不下:
ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
Type par_name1, // 4 space indent
Type par_name2,
Type par_name3) {
DoSomething(); // 2 space indent
...
}
注意以下幾點:
- 返回值總是和函數(shù)名在同一行;
- 左圓括號總是和函數(shù)名在同一行;
- 函數(shù)名和左圓括號間沒有空格;
- 圓括號與參數(shù)間沒有空格;
- 左大括號總在最后一個參數(shù)同一行的末尾處;
- 右大括號總是單獨位于函數(shù)最后一行;
- 右圓括號和左大括號間總是有一個空格;
- 函數(shù)聲明和實現(xiàn)處的所有形參名稱必須保持一致;
- 所有形參應盡可能對齊;
- 缺省縮進為 2 個空格;
- 換行后的參數(shù)保持 4 個空格的縮進;
如果函數(shù)聲明成 const
, 關(guān)鍵字 const
應與最后一個參數(shù)位于同一行:=
// Everything in this function signature fits on a single line
ReturnType FunctionName(Type par) const {
...
}
// This function signature requires multiple lines, but
// the const keyword is on the line with the last parameter.
ReturnType ReallyLongFunctionName(Type par1,
Type par2) const {
...
}
如果有些參數(shù)沒有用到, 在函數(shù)定義處將參數(shù)名注釋起來:
// Always have named parameters in interfaces.
class Shape {
public:
virtual void Rotate(double radians) = 0;
}
// Always have named parameters in the declaration.
class Circle : public Shape {
public:
virtual void Rotate(double radians);
}
// Comment out unused named parameters in definitions.
void Circle::Rotate(double /*radians*/) {}
Warning
// Bad - if someone wants to implement later, it's not clear what the
// variable means.
void Circle::Rotate(double) {}
Tip
盡量放在同一行, 否則, 將實參封裝在圓括號中.
函數(shù)調(diào)用遵循如下形式:
bool retval = DoSomething(argument1, argument2, argument3);
如果同一行放不下, 可斷為多行, 后面每一行都和第一個實參對齊, 左圓括號后和右圓括號前不要留空格:
bool retval = DoSomething(averyveryveryverylongargument1,
argument2, argument3);
如果函數(shù)參數(shù)很多, 出于可讀性的考慮可以在每行只放一個參數(shù):
bool retval = DoSomething(argument1,
argument2,
argument3,
argument4);
如果函數(shù)名非常長, 以至于超過 行最大長度, 可以將所有參數(shù)獨立成行:
if (...) {
...
...
if (...) {
DoSomethingThatRequiresALongFunctionName(
very_long_argument1, // 4 space indent
argument2,
argument3,
argument4);
}
Tip
傾向于不在圓括號內(nèi)使用空格. 關(guān)鍵字
else
另起一行.
對基本條件語句有兩種可以接受的格式. 一種在圓括號和條件之間有空格, 另一種沒有.
最常見的是沒有空格的格式. 哪種都可以, 但 保持一致性. 如果你是在修改一個文件, 參考當前已有格式. 如果是寫新的代碼, 參考目錄下或項目中其它文件. 還在徘徊的話, 就不要加空格了.
if (condition) { // no spaces inside parentheses
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
...
}
如果你更喜歡在圓括號內(nèi)部加空格:
if ( condition ) { // spaces inside parentheses - rare
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
...
}
注意所有情況下 if
和左圓括號間都有個空格. 右圓括號和左大括號之間也要有個空格:
Warning
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
分支則不允許:
Warning
// Not allowed - IF statement on one line when there is an ELSE clause
if (x) DoThis();
else DoThat();
通常, 單行語句不需要使用大括號, 如果你喜歡用也沒問題; 復雜的條件或循環(huán)語句用大括號可讀性會更好. 也有一些項目要求 if
必須總是使用大括號:
if (condition)
DoSomething(); // 2 space indent.
if (condition) {
DoSomething(); // 2 space indent.
}
但如果語句中某個 if-else
分支使用了大括號的話, 其它分支也必須使用:
Warning
// Not allowed - curly on IF but not ELSE
if (condition) {
foo;
} else
bar;
// Not allowed - curly on ELSE but not IF
if (condition)
foo;
else {
bar;
}
// Curly braces around both IF and ELSE required because
// one of the clauses used braces.
if (condition) {
foo;
} else {
bar;
}
Tip
switch
語句可以使用大括號分段. 空循環(huán)體應使用{}
或continue
.
switch
語句中的 case
塊可以使用大括號也可以不用, 取決于你的個人喜好. 如果用的話, 要按照下文所述的方法.
如果有不滿足 case
條件的枚舉值, switch
應該總是包含一個 default
匹配 (如果有輸入值沒有 case 去處理, 編譯器將報警). 如果 default
應該永遠執(zhí)行不到, 簡單的加條 assert
:
switch (var) {
case 0: { // 2 space indent
... // 4 space indent
break;
}
case 1: {
...
break;
}
default: {
assert(false);
}
}
空循環(huá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.
Warning
while (condition); // Bad - looks like part of do/while loop.
Tip
句點或箭頭前后不要有空格. 指針/地址操作符 (
*, &
) 之后不能有空格.
下面是指針和引用表達式的正確使用范例:
x = *p;
p = &x;
x = r.y;
x = r->y;
注意:
*
或 &
后沒有空格.在聲明指針變量或參數(shù)時, 星號與類型或變量名緊挨都可以:
// These are fine, space preceding.
char *c;
const string &str;
// These are fine, space following.
char* c; // but remember to do "char* c, *d, *e, ...;"!
const string& str;
Warning
char * c; // Bad - spaces on both sides of *
const string & str; // Bad - spaces on both sides of &
在單個文件內(nèi)要保持風格一致, 所以, 如果是修改現(xiàn)有文件, 要遵照該文件的風格.
Tip
如果一個布爾表達式超過 標準行寬, 斷行方式要統(tǒng)一一下.
下例中, 邏輯與 (&&
) 操作符總位于行尾:
if (this_one_thing > this_other_thing &&
a_third_thing == a_fourth_thing &&
yet_another & last_one) {
...
}
注意, 上例的邏輯與 (&&
) 操作符均位于行尾. 可以考慮額外插入圓括號, 合理使用的話對增強可讀性是很有幫助的.
Tip
return
表達式中不要用圓括號包圍.
函數(shù)返回時不要使用圓括號:
return x; // not return(x);
Tip
用
=
或()
均可.
在二者中做出選擇; 下面的方式都是正確的:
int x = 3;
int x(3);
string name("Some Name");
string name = "Some Name";
Tip
預處理指令不要縮進, 從行首開始.
即使預處理指令位于縮進代碼塊中, 指令也應從行首開始.
// Good - directives at beginning of line
if (lopsided_score) {
#if DISASTER_PENDING // Correct -- Starts at beginning of line
DropEverything();
#endif
BackToNormal();
}
Warning
// Bad - indented directives
if (lopsided_score) {
#if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line
DropEverything();
#endif // Wrong! Do not indent "#endif"
BackToNormal();
}
Tip
訪問控制塊的聲明依次序是
public:
,protected:
,private:
, 每次縮進 1 個空格.
類聲明 (對類注釋不了解的話, 參考 類注釋) 的基本格式如下:
class MyClass : public OtherClass {
public: // Note the 1 space indent!
MyClass(); // Regular 2 space indent.
explicit MyClass(int var);
~MyClass() {}
void SomeFunction();
void SomeFunctionThatDoesNothing() {
}
void set_some_var(int var) { some_var_ = var; }
int some_var() const { return some_var_; }
private:
bool SomeInternalFunction();
int some_var_;
int some_other_var_;
DISALLOW_COPY_AND_ASSIGN(MyClass);
};
注意事項:
public:
, protected:
, private:
要縮進 1 個空格.public
) 外, 其他關(guān)鍵詞前要空一行. 如果類比較小的話也可以不空.public
放在最前面, 然后是 protected
, 最后是 private
.Tip
構(gòu)造函數(shù)初始化列表放在同一行或按四格縮進并排幾行.
下面兩種初始化列表方式都可以接受:
// When it all fits on one line:
MyClass::MyClass(int var) : somevar(var), some_othervar(var + 1) {
或
// When it requires multiple lines, indent 4 spaces, putting the colon on
// the first initializer line:
MyClass::MyClass(int var)
: somevar(var), // 4 space indent
some_othervar(var + 1) { // lined up
...
DoSomething();
...
}
Tip
名字空間內(nèi)容不縮進.
名字空間 不要增加額外的縮進層次, 例如:
namespace {
void foo() { // Correct. No extra indentation within namespace.
...
}
} // namespace
不要縮進名字空間:
Warning
namespace {
// Wrong. Indented when it should not be.
void foo() {
...
}
} // namespace
Tip
水平留白的使用因地制宜. 永遠不要在行尾添加沒意義的留白.
常規(guī):
void f(bool b) { // Open braces should always have a space before them.
...
int i = 0; // Semicolons usually have no space before them.
int x[] = { 0 }; // Spaces inside braces for array initialization are
int x[] = {0}; // optional. If you use them, put them on both sides!
// Spaces around the colon in inheritance and initializer lists.
class Foo : public Bar {
public:
// For inline function implementations, put spaces between the braces
// and the implementation itself.
Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces.
void Reset() { baz_ = 0; } // Spaces separating braces from implementation.
...
添加冗余的留白會給其他人編輯時造成額外負擔. 因此, 行尾不要留空格. 如果確定一行代碼已經(jīng)修改完畢, 將多余的空格去掉; 或者在專門清理空格時去掉(確信沒有其他人在處理). (yospaly 注: 現(xiàn)在大部分代碼編輯器稍加設置后, 都支持自動刪除行首/行尾空格, 如果不支持, 考慮換一款編輯器或 IDE)
循環(huán)和條件語句:
if (b) { // Space after the keyword in conditions and loops.
} else { // Spaces around else.
}
while (test) {} // There is usually no space inside parentheses.
switch (i) {
for (int i = 0; i < 5; ++i) {
switch ( i ) { // Loops and conditions may have spaces inside
if ( test ) { // parentheses, but this is rare. Be consistent.
for ( int i = 0; i < 5; ++i ) {
for ( ; i < 5 ; ++i) { // For loops always have a space after the
... // semicolon, and may have a space before the
// semicolon.
switch (i) {
case 1: // No space before colon in a switch case.
...
case 2: break; // Use a space after a colon if there's code after it.
操作符:
x = 0; // Assignment operators always have spaces around
// them.
x = -5; // No spaces separating unary operators and their
++x; // arguments.
if (x && !y)
...
v = w * x + y / z; // Binary operators usually have spaces around them,
v = w*x + y/z; // but it's okay to remove spaces around factors.
v = w * (x + z); // Parentheses should have no spaces inside them.
模板和轉(zhuǎn)換:
vector<string> x; // No spaces inside the angle
y = static_cast<char*>(x); // brackets (< and >), before
// <, or between >( in a cast.
vector<char *> x; // Spaces between type and pointer are
// okay, but be consistent.
set<list<string> > x; // C++ requires a space in > >.
set< list<string> > x; // You may optionally make use
// symmetric spacing in < <.
Tip
垂直留白越少越好.
這不僅僅是規(guī)則而是原則問題了: 不在萬不得已, 不要使用空行. 尤其是: 兩個函數(shù)定義之間的空行不要超過 2 行, 函數(shù)體首尾不要留空行, 函數(shù)體中也不要隨意添加空行.
基本原則是: 同一屏可以顯示的代碼越多, 越容易理解程序的控制流. 當然, 過于密集的代碼塊和過于疏松的代碼塊同樣難看, 取決于你的判斷. 但通常是垂直留白越少越好.
Warning
函數(shù)首尾不要有空行
void Function() {
// Unnecessary blank lines before and after
}
Warning
代碼塊首尾不要有空行
while (condition) {
// Unnecessary blank line after
}
if (condition) {
// Unnecessary blank line before
}
if-else
塊之間空一行是可以接受的:
if (condition) {
// Some lines of code too small to move to another function,
// followed by a blank line.
} else {
// Another block of code
}
.
/->
操作符前后不留空格, *
/&
不要前后都留, 一個就可, 靠左靠右依各人喜好;=
還是 ()
依個人喜好, 統(tǒng)一就好;return
不要加 ()
;.cc
文件的函數(shù)實現(xiàn)處, 左大括號位于行首), 我的理解是代碼看上去比較簡約, 想想行首除了函數(shù)體被一對大括號封在一起之外, 只有右大括號的代碼看上去確實也舒服; Windows 風格將左大括號置于行首的優(yōu)點是匹配情況一目了然.
更多建議: