原文地址:Google C++ Style Guide
代碼風(fēng)格和格式確實(shí)比較隨意,但一個(gè)項(xiàng)目中所有人遵循同一風(fēng)格是非常容易的,作為個(gè)人未必同意下述格式規(guī)則的每一處,但整個(gè)項(xiàng)目服從統(tǒng)一的編程風(fēng)格是很重要的,這樣做才能讓所有人在閱讀和理解代碼時(shí)更加容易。
1. 行長(zhǎng)度(Line Length)
每一行代碼字符數(shù)不超過(guò)80。
我們也認(rèn)識(shí)到這條規(guī)則是存有爭(zhēng)議的,但如此多的代碼都遵照這一規(guī)則,我們感覺(jué)一致性更重要。
優(yōu)點(diǎn):提倡該原則的人認(rèn)為強(qiáng)迫他們調(diào)整編輯器窗口大小很野蠻。很多人同時(shí)并排開(kāi)幾個(gè)窗口,根本沒(méi)有多余空間拓寬某個(gè)窗口,人們將窗口最大尺寸加以限定,一致使用80列寬,為什么要改變呢?
缺點(diǎn):反對(duì)該原則的人則認(rèn)為更寬的代碼行更易閱讀,80列的限制是上個(gè)世紀(jì)60年代的大型機(jī)的古板缺陷;現(xiàn)代設(shè)備具有更寬的顯示屏,很輕松的可以顯示更多代碼。
結(jié)論:80個(gè)字符是最大值。例外:
1) 如果一行注釋包含了超過(guò)80字符的命令或URL,出于復(fù)制粘貼的方便可以超過(guò)80字符;
2) 包含長(zhǎng)路徑的可以超出80列,盡量避免;
3) 頭文件保護(hù)(防止重復(fù)包含第一篇)可以無(wú)視該原則。
2. 非ASCII字符(Non-ASCII Characters)
盡量不使用非ASCII字符,使用時(shí)必須使用UTF-8格式。
哪怕是英文,也不應(yīng)將用戶(hù)界面的文本硬編碼到源代碼中,因此非ASCII字符要少用。特殊情況下可以適當(dāng)包含此類(lèi)字符,如,代碼分析外部數(shù)據(jù)文件時(shí),可以適當(dāng)硬編碼數(shù)據(jù)文件中作為分隔符的非ASCII字符串;更常用的是(不需要本地化的)單元測(cè)試代碼可能包含非ASCII字符串。此類(lèi)情況下,應(yīng)使用UTF-8格式,因?yàn)楹芏喙ぞ叨伎梢岳斫夂吞幚砥渚幋a,十六進(jìn)制編碼也可以,尤其是在增強(qiáng)可讀性的情況下——如"\xEF\xBB\xBF"
是Unicode的zero-width no-break space字符,以UTF-8格式包含在源文件中是不可見(jiàn)的。
3. 空格還是制表位(Spaces vs. Tabs)
只使用空格,每次縮進(jìn)2個(gè)空格。
使用空格進(jìn)行縮進(jìn),不要在代碼中使用tabs,設(shè)定編輯器將tab轉(zhuǎn)為空格。
譯者注:在前段時(shí)間的關(guān)于Debian開(kāi)發(fā)學(xué)習(xí)日記一文中,曾給出針對(duì)C/C++編碼使用的vim配置。
4. 函數(shù)聲明與定義(Function Declarations and Definitions)
返回類(lèi)型和函數(shù)名在同一行,合適的話(huà),參數(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();
...
}
甚至連第一個(gè)參數(shù)都放不下:
ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
Type par_name1, // 4 space indent
Type par_name2,
Type par_name3) {
DoSomething(); // 2 space indent
...
}
注意以下幾點(diǎn):
1) 返回值總是和函數(shù)名在同一行;
2) 左圓括號(hào)(open parenthesis)總是和函數(shù)名在同一行;
3) 函數(shù)名和左圓括號(hào)間沒(méi)有空格;
4) 圓括號(hào)與參數(shù)間沒(méi)有空格;
5) 左大括號(hào)(open curly brace)總在最后一個(gè)參數(shù)同一行的末尾處;
6) 右大括號(hào)(close curly brace)總是單獨(dú)位于函數(shù)最后一行;
7) 右圓括號(hào)(close parenthesis)和左大括號(hào)間總是有一個(gè)空格;
8) 函數(shù)聲明和實(shí)現(xiàn)處的所有形參名稱(chēng)必須保持一致;
9) 所有形參應(yīng)盡可能對(duì)齊;
10) 缺省縮進(jìn)為2個(gè)空格;
11) 獨(dú)立封裝的參數(shù)保持4個(gè)空格的縮進(jìn)。
如果函數(shù)為const
的,關(guān)鍵字const
應(yīng)與最后一個(gè)參數(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ù)沒(méi)有用到,在函數(shù)定義處將參數(shù)名注釋起來(lái):
// 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*/) {}
// Bad - if someone wants to implement later, it's not clear what the
// variable means.
void Circle::Rotate(double) {}
譯者注:關(guān)于UNIX/Linux風(fēng)格為什么要把左大括號(hào)置于行尾(.cc文件的函數(shù)實(shí)現(xiàn)處,左大括號(hào)位于行首),我的理解是代碼看上去比較簡(jiǎn)約,想想行首除了函數(shù)體被一對(duì)大括號(hào)封在一起之外,只有右大括號(hào)的代碼看上去確實(shí)也舒服;Windows風(fēng)格將左大括號(hào)置于行首的優(yōu)點(diǎn)是匹配情況一目了然。
5. 函數(shù)調(diào)用(Function Calls)
盡量放在同一行,否則,將實(shí)參封裝在圓括號(hào)中。
函數(shù)調(diào)用遵循如下形式:
bool retval = DoSomething(argument1, argument2, argument3);
如果同一行放不下,可斷為多行,后面每一行都和第一個(gè)實(shí)參對(duì)齊,左圓括號(hào)后和右圓括號(hào)前不要留空格:
bool retval = DoSomething(averyveryveryverylongargument1,
argument2, argument3);
如果函數(shù)參數(shù)比較多,可以出于可讀性的考慮每行只放一個(gè)參數(shù):
bool retval = DoSomething(argument1,
argument2,
argument3,
argument4);
如果函數(shù)名太長(zhǎng),以至于超過(guò)行最大長(zhǎng)度,可以將所有參數(shù)獨(dú)立成行:
if (...) {
...
...
if (...) {
DoSomethingThatRequiresALongFunctionName(
very_long_argument1, // 4 space indent
argument2,
argument3,
argument4);
}
6. 條件語(yǔ)句(Conditionals)
更提倡不在圓括號(hào)中添加空格,關(guān)鍵字else
另起一行。
對(duì)基本條件語(yǔ)句有兩種可以接受的格式,一種在圓括號(hào)和條件之間有空格,一種沒(méi)有。
最常見(jiàn)的是沒(méi)有空格的格式,那種都可以,還是一致性為主。如果你是在修改一個(gè)文件,參考當(dāng)前已有格式;如果是寫(xiě)新的代碼,參考目錄下或項(xiàng)目中其他文件的格式,還在徘徊的話(huà),就不要加空格了。
if (condition) { // no spaces inside parentheses
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
...
}
如果你傾向于在圓括號(hào)內(nèi)部加空格:
if ( condition ) { // spaces inside parentheses - rare
... // 2 space indent.
} else { // The else goes on the same line as the closing brace.
...
}
注意所有情況下if
和左圓括號(hào)間有個(gè)空格,右圓括號(hào)和左大括號(hào)(如果使用的話(huà))間也要有個(gè)空格:
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 {.
有些條件語(yǔ)句寫(xiě)在同一行以增強(qiáng)可讀性,只有當(dāng)語(yǔ)句簡(jiǎn)單并且沒(méi)有使用else子句
時(shí)使用:
if (x == kFoo) return new Foo();
if (x == kBar) return new Bar();
如果語(yǔ)句有else
分支是不允許的:
// Not allowed - IF statement on one line when there is an ELSE clause
if (x) DoThis();
else DoThat();
通常,單行語(yǔ)句不需要使用大括號(hào),如果你喜歡也無(wú)可厚非,也有人要求if
必須使用大括號(hào):
if (condition)
DoSomething(); // 2 space indent.
if (condition) {
DoSomething(); // 2 space indent.
}
但如果語(yǔ)句中哪一分支使用了大括號(hào)的話(huà),其他部分也必須使用:
// 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;
}
7. 循環(huán)和開(kāi)關(guān)選擇語(yǔ)句(Loops and Switch Statements)
switch
語(yǔ)句可以使用大括號(hào)分塊;空循環(huán)體應(yīng)使用{}
或continue
。
switch
語(yǔ)句中的case
塊可以使用大括號(hào)也可以不用,取決于你的喜好,使用時(shí)要依下文所述。
如果有不滿(mǎn)足case
枚舉條件的值,要總是包含一個(gè)default
(如果有輸入值沒(méi)有case
去處理,編譯器將報(bào)警)。如果default
永不會(huì)執(zhí)行,可以簡(jiǎn)單的使用assert
:
switch (var) {
case 0: { // 2 space indent
... // 4 space indent
break;
}
case 1: {
...
break;
}
default: {
assert(false);
}
}
空循環(huán)體應(yīng)使用{}
或continue
,而不是一個(gè)簡(jiǎn)單的分號(hào):
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.
8. 指針和引用表達(dá)式(Pointers and Reference Expressions)
句點(diǎn)(.
)或箭頭(->
)前后不要有空格,指針/地址操作符(*、&
)后不要有空格。
下面是指針和引用表達(dá)式的正確范例:
x = *p;
p = &x;
x = r.y;
x = r->y;
注意:
1) 在訪問(wèn)成員時(shí),句點(diǎn)或箭頭前后沒(méi)有空格;
2) 指針操作符*
或&
后沒(méi)有空格。
在聲明指針變量或參數(shù)時(shí),星號(hào)與類(lèi)型或變量名緊挨都可以:
// 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;
char * c; // Bad - spaces on both sides of *
const string & str; // Bad - spaces on both sides of &
同一個(gè)文件(新建或現(xiàn)有)中起碼要保持一致。
譯者注:個(gè)人比較習(xí)慣與變量緊挨的方式。
9. 布爾表達(dá)式(Boolean Expressions)
如果一個(gè)布爾表達(dá)式超過(guò)標(biāo)準(zhǔn)行寬(80字符),如果斷行要統(tǒng)一一下。
下例中,邏輯與(&&
)操作符總位于行尾:
if (this_one_thing > this_other_thing &&
a_third_thing == a_fourth_thing &&
yet_another & last_one) {
...
}
兩個(gè)邏輯與(&&
)操作符都位于行尾,可以考慮額外插入圓括號(hào),合理使用的話(huà)對(duì)增強(qiáng)可讀性是很有幫助的。
譯者注:個(gè)人比較習(xí)慣邏輯運(yùn)算符位于行首,邏輯關(guān)系一目了然,各人喜好而已,至于加不加圓括號(hào)的問(wèn)題,如果你對(duì)優(yōu)先級(jí)了然于胸的話(huà)可以不加,但可讀性總是差了些。
10. 函數(shù)返回值(Return Values)
return
表達(dá)式中不要使用圓括號(hào)。
函數(shù)返回時(shí)不要使用圓括號(hào):
return x; // not return(x);
11. 變量及數(shù)組初始化(Variable and Array Initialization)
選擇=
還是()
。
需要做二者之間做出選擇,下面的形式都是正確的:
int x = 3;
int x(3);
string name("Some Name");
string name = "Some Name";
12. 預(yù)處理指令(Preprocessor Directives)
預(yù)處理指令不要縮進(jìn),從行首開(kāi)始。
即使預(yù)處理指令位于縮進(jìn)代碼塊中,指令也應(yīng)從行首開(kāi)始。
// Good - directives at beginning of line
if (lopsided_score) {
#if DISASTER_PENDING // Correct -- Starts at beginning of line
DropEverything();
#endif
BackToNormal();
}
// 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();
}
13. 類(lèi)格式(Class Format)
聲明屬性依次序是public:
、protected:
、private:
,每次縮進(jìn)1個(gè)空格(譯者注,為什么不是兩個(gè)呢?也有人提倡private
在前,對(duì)于聲明了哪些數(shù)據(jù)成員一目了然,還有人提倡依邏輯關(guān)系將變量與操作放在一起,都有道理:-)
)。
類(lèi)聲明(對(duì)類(lèi)注釋不了解的話(huà),參考第六篇中的類(lèi)注釋一節(jié))的基本格式如下:
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);
};
注意:
1) 所以基類(lèi)名應(yīng)在80列限制下盡量與子類(lèi)名放在同一行;
2) 關(guān)鍵詞public:、
protected:
、private:
要縮進(jìn)1個(gè)空格(譯者注,MSVC多使用tab縮進(jìn),且這三個(gè)關(guān)鍵詞沒(méi)有縮進(jìn));
3) 除第一個(gè)關(guān)鍵詞(一般是public)外,其他關(guān)鍵詞前空一行,如果類(lèi)比較小的話(huà)也可以不空;
4) 這些關(guān)鍵詞后不要空行;
5) public
放在最前面,然后是protected
和private
;
6) 關(guān)于聲明次序參考第三篇聲明次序一節(jié)。
14. 初始化列表(Initializer Lists)
構(gòu)造函數(shù)初始化列表放在同一行或按四格縮進(jìn)并排幾行。
兩種可以接受的初始化列表格式:
// When it all fits on one line:
MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {
或
// When it requires multiple lines, indent 4 spaces, putting the colon on
// the first initializer line:
MyClass::MyClass(int var)
: some_var_(var), // 4 space indent
some_other_var_(var + 1) { // lined up
...
DoSomething();
...
}
15. 命名空間格式化(Namespace Formatting)
命名空間內(nèi)容不縮進(jìn)。
命名空間不添加額外縮進(jìn)層次,例如:
namespace {
void foo() { // Correct. No extra indentation within namespace.
...
}
} // namespace
不要縮進(jìn):
namespace {
// Wrong. Indented when it should not be.
void foo() {
...
}
} // namespace
16. 水平留白(Horizontal Whitespace)
水平留白的使用因地制宜。不要在行尾添加無(wú)謂的留白。
普通:
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.
...
添加冗余的留白會(huì)給其他人編輯時(shí)造成額外負(fù)擔(dān),因此,不要加入多余的空格。如果確定一行代碼已經(jīng)修改完畢,將多余的空格去掉;或者在專(zhuān)門(mén)清理空格時(shí)去掉(確信沒(méi)有其他人在使用)。
循環(huán)和條件語(yǔ)句:
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 < <.
17. 垂直留白(Vertical Whitespace)
垂直留白越少越好。
這不僅僅是規(guī)則而是原則問(wèn)題了:不是非常有必要的話(huà)就不要使用空行。尤其是:不要在兩個(gè)函數(shù)定義之間空超過(guò)2行,函數(shù)體頭、尾不要有空行,函數(shù)體中也不要隨意添加空行。
基本原則是:同一屏可以顯示越多的代碼,程序的控制流就越容易理解。當(dāng)然,過(guò)于密集的代碼塊和過(guò)于疏松的代碼塊同樣難看,取決于你的判斷,但通常是越少越好。
函數(shù)頭、尾不要有空行:
void Function() {
// Unnecessary blank lines before and after
}
代碼塊頭、尾不要有空行:
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
}
______________________________________
譯者:首先說(shuō)明,對(duì)于代碼格式,因人、因系統(tǒng)各有優(yōu)缺點(diǎn),但同一個(gè)項(xiàng)目中遵循同一標(biāo)準(zhǔn)還是有必要的:
1. 行寬原則上不超過(guò)80列,把22寸的顯示屏都占完,怎么也說(shuō)不過(guò)去;
2. 盡量不使用非ASCII字符,如果使用的話(huà),參考UTF-8格式(尤其是UNIX/Linux下,Windows下可以考慮寬字符),盡量不將字符串常量耦合到代碼中,比如獨(dú)立出資源文件,這不僅僅是風(fēng)格問(wèn)題了;
3. UNIX/Linux下無(wú)條件使用空格,MSVC的話(huà)使用Tab也無(wú)可厚非;
4. 函數(shù)參數(shù)、邏輯條件、初始化列表:要么所有參數(shù)和函數(shù)名放在同一行,要么所有參數(shù)并排分行;
5. 除函數(shù)定義的左大括號(hào)可以置于行首外,包括函數(shù)/類(lèi)/結(jié)構(gòu)體/枚舉聲明、各種語(yǔ)句的左大括號(hào)置于行尾,所有右大括號(hào)獨(dú)立成行;
6. ./->操作符前后不留空格,*/&不要前后都留,一個(gè)就可,靠左靠右依各人喜好;
7. 預(yù)處理指令/命名空間不使用額外縮進(jìn),類(lèi)/結(jié)構(gòu)體/枚舉/函數(shù)/語(yǔ)句使用縮進(jìn);
8. 初始化用=還是()依個(gè)人喜好,統(tǒng)一就好;
9. return不要加();
10. 水平/垂直留白不要濫用,怎么易讀怎么來(lái)。