1. 程式人生 > >3. 我使用的C/C++編寫規範之格式

3. 我使用的C/C++編寫規範之格式

lse word ble 簡單 編輯器 func 水平 cin 操作符

閑來無事,把自用的C/C++編程規範整理一下。內容主要來自Google與華為,並參考了一點微軟。


  整個項目服從統一的編程風格是很重要的,這樣才能讓所有人在閱讀和理解代碼時更加容易。
 
1.行長度
  每一行代碼字符數不超過 80。
  例外情況:
  1) 如果一行註釋包含了超過80字符的命令或URL,出於復制粘貼的方便可以超過80字符;
  2) 包含長路徑的可以超出80列,盡量避免;
  3) 頭文件保護可以無視該原則。 
 
2.非ASCII字符
  盡量不使用非ASCII字符,使用時必須使用 UTF-8 格式。
  哪怕是英文,也不應將用戶界面的文本硬編碼到源代碼中,因此非ASCII字符要少用。特殊情況下可以適當包含此類字符.例如,代碼分析外部數據文件時,可以適當硬編碼數據文件中作為分隔符的非ASCII字符串;更常用的是(不需要本地化的)單元測試代碼可能包含非ASCII字符串。此類情況下,應使用UTF-8格式,因為很多工具都可以理解和處理其編碼,十六進制編碼也可以,尤其是在增強可讀性的情況下——如"\verb \xEF\xBB\xBF"是Unicode的zero-width no-break space字符,以 UTF-8格式包含在源文件中是不可見的。

 
3.縮進
  只使用空格,每次縮進2個空格。不要在代碼中使用tabs,設定編輯器將tab轉為空格。
 
4.函數聲明與定義
  返回類型和函數名在同一行,合適的話,參數也放在同一行。
  函數看上去像這樣:

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

 
5.函數調用
  盡量放在同一行,否則,將實參封裝在圓括號中。
  函數調用遵循如下形式:

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.條件語句
  不在圓括號中添加空格,關鍵字 else 另起一行。

if (condition) { // no spaces inside parentheses
  ... // 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.循環和開關選擇語句
  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.指針和引用表達式
  句點(.)或箭頭(->)前後不要有空格,指針/地址操作符(*、&)後不要有空格。
  下面是指針和引用表達式的正確範例:

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.布爾表達式
  如果一個布爾表達式超過標準行寬(80 字符),如果斷行要統一一下。
  下例中,邏輯與(\&\&)操作符總位於行尾:

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

  兩個邏輯與(&&)操作符都位於行尾,可以考慮額外插入圓括號,合理使用的話對增強可讀性是很有幫助的。
 
10.函數返回值
  return 表達式中不要使用圓括號。
  函數返回時不要使用圓括號:

return x; // not return(x);

 
11.變量及數組初始化
  選擇=還是()。
  需要做二者之間做出選擇,下面的形式都是正確的:

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

 
12.預處理指令
  預處理指令不要縮進,從行首開始。
  即使預處理指令位於縮進代碼塊中,指令也應從行首開始。

// 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.類格式
  聲明屬性依次序是 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);
};

  註意:
  1)所有基類名應在80列限制下盡量與子類名在同一行;
  2)關鍵詞 public:、protected:、private:要縮進 1 個空格;
  3)除第一個關鍵詞(一般是 public)外,其他關鍵詞前空一行,如果類比較小的話也可以。
  不空;
  4)這些關鍵詞後不要空行;
  5)public 放在最前面,然後是protected和private;
 
14.初始化列表
  構造函數初始化列表放在同一行或按四格縮進並排幾行。
  兩種可以接受的初始化列表格式:

// 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 {
void foo() { // Correct. No extra indentation within namespace.
  ...
}
} // namespace

  不要縮進:

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

 
16.水平留白
  水平留白的使用因地制宜。不要在行尾添加無謂的留白。
  普通:

void f(bool b) { // 左大括號之前總是有一個空格。
  ...
int i = 0; // 分號前通常沒有空格。
int x[] = {0};   // 數組初始化時大括號內不留空格。
class Foo : public Bar {
  public:
  // 對於內聯函數實現,在大括號和實現本身之間放置空格。
  Foo(int b) : Bar(), baz_(b) {} // 空括號內沒有空格。
  void Reset() { baz_ = 0; } // 用空格分開大括號與實現。
  ...

  添加冗余的留白會給其他人編輯時造成額外負擔,因此,不要加入多余的空格。如果確定一行代碼已經修改完畢,將多余的空格去掉;或者在專門清理空格時去掉(確信沒有其他人在使用)。
  循環和條件語句:

if (b) {        // 在條件和循環的關鍵字之後加空格。
} else {        // else左右都有空格。
}
while (test) {} // 圓括號內通常沒有空格。
switch (i) {
for (int i = 0; i < 5; ++i) {
switch ( i ) {  // 循環和條件可能在圓括號內有空格,但這很少見。註意保持一致。
if ( test ) {
for ( int i = 0; i < 5; ++i ) {
for ( ; i < 5 ; ++i) { // For循環在分號後總是有一個空格,
...                    // 並且在分號之前可能有一個空格。
switch (i) {
case 1:                // switch語句內case中的冒號前沒有空格。
...
case 2: break;         // 如果後面有代碼,則在冒號後面使用空格。

  模板和轉換:

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.垂直留白
  垂直留白越少越好。
  這不僅僅是規則而是原則問題了:不是非常有必要的話就不要使用空行。尤其是:不要在兩個函數定義之間空超過2行,函數體頭、尾不要有空行,函數體中也不要隨意添加空行。
  基本原則是:同一屏可以顯示越多的代碼,程序的控制流就越容易理解。當然,過於密集的代碼塊和過於疏松的代碼塊同樣難看,取決於你的判斷,但通常是越少越好。
  函數頭、尾不要有空行:

void Function() {
  // Unnecessary blank lines before and after
}

  代碼塊頭、尾不要有空行:

while (condition) {
  // Unnecessary blank line after
}
if (condition) {
  // Unnecessary blank line before
}

 
18.補充規定與說明
  18.1 多個短語句(包括賦值語句)不允許寫在同一行內,即一行只寫一條語句。
  示例:
  不好的排版:

int a = 5; int b= 10;

  好的排版:

int a = 5;
int b = 10;

  18.2 逗號、分號只在後面加空格,雙目操作符的前後要加空格,->與.前後不加空格。
  18.3 註釋符與註釋內容之間要用一個空格進行分隔。

3. 我使用的C/C++編寫規範之格式