天天看點

Google C++程式設計風格指南(七)

原文位址:Google C++ Style Guide

  • 格式

代碼風格和格式确實比較随意,但一個項目中所有人遵循同一風格是非常容易的,作為個人未必同意下述格式規則的每一處,但整個項目服從統一的程式設計風格是很重要的,這樣做才能讓所有人在閱讀和了解代碼時更加容易。

1. 行長度(Line Length)

每一行代碼字元數不超過80。

我們也認識到這條規則是存有争議的,但如此多的代碼都遵照這一規則,我們感覺一緻性更重要。

優點:提倡該原則的人認為強迫他們調整編輯器視窗大小很野蠻。很多人同時并排開幾個視窗,根本沒有多餘空間拓寬某個視窗,人們将視窗最大尺寸加以限定,一緻使用80列寬,為什麼要改變呢?

缺點:反對該原則的人則認為更寬的代碼行更易閱讀,80列的限制是上個世紀60年代的大型機的古闆缺陷;現代裝置具有更寬的顯示屏,很輕松的可以顯示更多代碼。

結論:80個字元是最大值。例外:

1) 如果一行注釋包含了超過80字元的指令或URL,出于複制粘貼的友善可以超過80字元;

2) 包含長路徑的可以超出80列,盡量避免;

3) 頭檔案保護(防止重複包含第一篇)可以無視該原則。

2. 非ASCII字元(Non-ASCII Characters)

盡量不使用非ASCII字元,使用時必須使用UTF-8格式。

哪 怕是英文,也不應将使用者界面的文本寫死到源代碼中,是以非ASCII字元要少用。特殊情況下可以适當包含此類字元,如,代碼分析外部資料檔案時,可以适 當寫死資料檔案中作為分隔符的非ASCII字元串;更常用的是(不需要本地化的)單元測試代碼可能包含非ASCII字元串。此類情況下,應使用UTF- 8格式,因為很多工具都可以了解和處理其編碼,十六進制編碼也可以,尤其是在增強可讀性的情況下——如

"/xEF/xBB/xBF"

是Unicode的zero-width no-break space字元,以UTF-8格式包含在源檔案中是不可見的。

3. 空格還是制表位(Spaces vs. Tabs)

隻使用空格,每次縮進2個空格。

使用空格進行縮進,不要在代碼中使用tabs,設定編輯器将tab轉為空格。

譯者注:在前段時間的關于Debian開發學習日記一文中,曾給出針對C/C++編碼使用的vim配置。

4. 函數聲明與定義(Function Declarations and Definitions)

傳回類型和函數名在同一行,合适的話,參數也放在同一行。

函數看上去像這樣:

ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
  DoSomething();
  ...
}

      

如果同一行文本較多,容不下所有參數:

ReturnType ClassName::ReallyLongFunctionName(Type par_name1,
                                             Type par_name2,
                                             Type par_name3) {
  DoSomething();
  ...
}

      

甚至連第一個參數都放不下:

ReturnType LongClassName::ReallyReallyReallyLongFunctionName(
    Type par_name1,  // 4 space indent
    Type par_name2,
    Type par_name3) {
  DoSomething();  // 2 space indent
  ...
}

      

注意以下幾點:

1) 傳回值總是和函數名在同一行;

2) 左圓括号(open parenthesis)總是和函數名在同一行;

3) 函數名和左圓括号間沒有空格;

4) 圓括号與參數間沒有空格;

5) 左大括号(open curly brace)總在最後一個參數同一行的末尾處;

6) 右大括号(close curly brace)總是單獨位于函數最後一行;

7) 右圓括号(close parenthesis)和左大括号間總是有一個空格;

8) 函數聲明和實作處的所有形參名稱必須保持一緻;

9) 所有形參應盡可能對齊;

10) 預設縮進為2個空格;

11) 獨立封裝的參數保持4個空格的縮進。

如果函數為

const

的,關鍵字

const

應與最後一個參數位于同一行。

// 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 {
  ...
}

      

如果有些參數沒有用到,在函數定義處将參數名注釋起來:

// 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) {}

      

譯者注:關于UNIX/Linux風格為什麼要把左大括号置于行尾(.cc檔案的函數實作處,左大括号位于行首),我的了解是代碼 看上去比較簡約,想想行首除了函數體被一對大括号封在一起之外,隻有右大括号的代碼看上去确實也舒服;Windows風格将左大括号置于行首的優點是比對 情況一目了然。

5. 函數調用(Function Calls)

盡量放在同一行,否則,将實參封裝在圓括号中。

函數調用遵循如下形式:

bool retval = DoSomething(argument1, argument2, argument3);

      

如果同一行放不下,可斷為多行,後面每一行都和第一個實參對齊,左圓括号後和右圓括号前不要留白格:

bool retval = DoSomething(averyveryveryverylongargument1,
                          argument2, argument3);

      

如果函數參數比較多,可以出于可讀性的考慮每行隻放一個參數:

bool retval = DoSomething(argument1,
                          argument2,
                          argument3,
                          argument4);

      

如果函數名太長,以至于超過行最大長度,可以将所有參數獨立成行:

if (...) {
  ...
  ...
  if (...) {
    DoSomethingThatRequiresALongFunctionName(
        very_long_argument1,  // 4 space indent
        argument2,
        argument3,
        argument4);
  }

      

6. 條件語句(Conditionals)

更提倡不在圓括号中添加空格,關鍵字

else

另起一行。

對基本條件語句有兩種可以接受的格式,一種在圓括号和條件之間有空格,一種沒有。

最常見的是沒有空格的格式,那種都可以,還是一緻性為主。如果你是在修改一個檔案,參考目前已有格式;如果是寫新的代碼,參考目錄下或項目中其他檔案的格式,還在徘徊的話,就不要加空格了。

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) {
  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. 循環和開關選擇語句(Loops and Switch Statements)

switch

語句可以使用大括号分塊;空循環體應使用

{}

continue

switch

語句中的

case

塊可以使用大括号也可以不用,取決于你的喜好,使用時要依下文所述。

如果有不滿足

case

枚舉條件的值,要總是包含一個

default

(如果有輸入值沒有

case

去處理,編譯器将報警)。如果

default

永不會執行,可以簡單的使用

assert

switch (var) {
  case 0: {  // 2 space indent
    ...      // 4 space indent
    break;
  }
  case 1: {
    ...
    break;
  }
  default: {
    assert(false);
  }
}

      

空循環體應使用

{}

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.

      

8. 指針和引用表達式(Pointers and Reference Expressions)

句點(

.

)或箭頭(

->

)前後不要有空格,指針/位址操作符(

*、&

)後不要有空格。

下面是指針和引用表達式的正确範例:

x = *p;
p = &x;
x = r.y;
x = r->y;

      

注意:

1) 在通路成員時,句點或箭頭前後沒有空格;

2) 指針操作符

*

&

後沒有空格。

在聲明指針變量或參數時,星号與類型或變量名緊挨都可以:

// 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 &

      

同一個檔案(建立或現有)中起碼要保持一緻。

譯者注:個人比較習慣與變量緊挨的方式。

9. 布爾表達式(Boolean Expressions)

如果一個布爾表達式超過标準行寬(80字元),如果斷行要統一一下。

下例中,邏輯與(

&&

)操作符總位于行尾:

if (this_one_thing > this_other_thing &&
    a_third_thing == a_fourth_thing &&
    yet_another & last_one) {
  ...
}

      

兩個邏輯與(

&&

)操作符都位于行尾,可以考慮額外插入圓括号,合理使用的話對增強可讀性是很有幫助的。

譯者注:個人比較習慣邏輯運算符位于行首,邏輯關系一目了然,各人喜好而已,至于加不加圓括号的問題,如果你對優先級了然于胸的話可以不加,但可讀性總是差了些。

10. 函數傳回值(Return Values)

return

表達式中不要使用圓括号。

函數傳回時不要使用圓括号:

return x;  // not return(x);

      

11. 變量及數組初始化(Variable and Array Initialization)

選擇

=

還是

()

需要做二者之間做出選擇,下面的形式都是正确的:

int x = 3;
int x(3);
string name("Some Name");
string name = "Some Name";

      

12. 預處理指令(Preprocessor Directives)

預處理指令不要縮進,從行首開始。

即使預處理指令位于縮進代碼塊中,指令也應從行首開始。

// 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. 類格式(Class Format)

聲明屬性依次序是

public:

protected:

private:

,每次縮進1個空格(譯者注,為什麼不是兩個呢?也有人提倡

private

在前,對于聲明了哪些資料成員一目了然,還有人提倡依邏輯關系将變量與操作放在一起,都有道理

:-)

)。

類聲明(對類注釋不了解的話,參考第六篇中的類注釋一節)的基本格式如下:

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) 是以基類名應在80列限制下盡量與子類名放在同一行;

2) 關鍵詞

public:、

protected:

private:

要縮進1個空格(譯者注,MSVC多使用tab縮進,且這三個關鍵詞沒有縮進);

3) 除第一個關鍵詞(一般是

public)外,其他關鍵詞前空一行,如果類比較小的話也可以不空;

4) 這些關鍵詞後不要空行;

5)

public

放在最前面,然後是

protected

private

6) 關于聲明次序參考第三篇聲明次序一節。

14. 初始化清單(Initializer Lists)

構造函數初始化清單放在同一行或按四格縮進并排幾行。

兩種可以接受的初始化清單格式:

// 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)

命名空間内容不縮進。

命名空間不添加額外縮進層次,例如:

namespace {

void foo() {  // Correct.  No extra indentation within namespace.
  ...
}

}  // namespace

      

不要縮進:

namespace {

  // Wrong.  Indented when it should not be.
  void foo() {
    ...
  }

}  // namespace

      

16. 水準留白(Horizontal Whitespace)

水準留白的使用因地制宜。不要在行尾添加無謂的留白。

普通:

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.
  ...

      

添加備援的留白會給其他人編輯時造成額外負擔,是以,不要加入多餘的空格。如果确定一行代碼已經修改完畢,将多餘的空格去掉;或者在專門清理空格時去掉(确信沒有其他人在使用)。

循環和條件語句:

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.

      

模闆和轉換:

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)

垂直留白越少越好。

這不僅僅是規則而是原則問題了:不是非常有必要的話就不要使用空行。尤其是:不要在兩個函數定義之間空超過2行,函數體頭、尾不要有空行,函數體中也不要随意添加空行。

基本原則是:同一屏可以顯示越多的代碼,程式的控制流就越容易了解。當然,過于密集的代碼塊和過于疏松的代碼塊同樣難看,取決于你的判斷,但通常是越少越好。

函數頭、尾不要有空行:

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
}

      

______________________________________

譯者:首先說明,對于代碼格式,因人、因系統各有優缺點,但同一個項目中遵循同一标準還是有必要的:

1. 行寬原則上不超過80列,把22寸的顯示屏都占完,怎麼也說不過去;

2. 盡量不使用非ASCII字元,如果使用的話,參考UTF-8格式(尤其是UNIX/Linux下,Windows下可以考慮寬字元),盡量不将字元串常量耦合到代碼中,比如獨立出資源檔案,這不僅僅是風格問題了;

3. UNIX/Linux下無條件使用空格,MSVC的話使用Tab也無可厚非;

4. 函數參數、邏輯條件、初始化清單:要麼所有參數和函數名放在同一行,要麼所有參數并排分行;

5. 除函數定義的左大括号可以置于行首外,包括函數/類/結構體/枚舉聲明、各種語句的左大括号置于行尾,所有右大括号獨立成行;

6. ./->操作符前後不留白格,*/&不要前後都留,一個就可,靠左靠右依各人喜好;

7. 預處理指令/命名空間不使用額外縮進,類/結構體/枚舉/函數/語句使用縮進;

8. 初始化用=還是()依個人喜好,統一就好;

9. return不要加();

10. 水準/垂直留白不要濫用,怎麼易讀怎麼來。

繼續閱讀