代碼風格和格式確實比較隨意, 但一個項目中所有人遵循同一風格是非常容易的. 個體未必同意下述每一處格式規則, 但整個項目服從統一的編程風格是很重要的, 只有這樣才能讓所有人能很輕松的閱讀和理解代碼.
另外, 我們寫了一個 [emacs 配置文件](http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el) [http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el] 來幫助你正確的格式化代碼.
## 8.1. 行長度
> Tip
> 每一行代碼字符數不超過 80.
我們也認識到這條規則是有爭議的, 但很多已有代碼都已經遵照這一規則, 我們感覺一致性更重要.
優點:提倡該原則的人主張強迫他們調整編輯器窗口大小很野蠻. 很多人同時并排開幾個代碼窗口, 根本沒有多余空間拉伸窗口. 大家都把窗口最大尺寸加以限定, 并且 80 列寬是傳統標準. 為什么要改變呢?缺點:反對該原則的人則認為更寬的代碼行更易閱讀. 80 列的限制是上個世紀 60 年代的大型機的古板缺陷; 現代設備具有更寬的顯示屏, 很輕松的可以顯示更多代碼.結論:
80 個字符是最大值.
特例:
- 如果一行注釋包含了超過 80 字符的命令或 URL, 出于復制粘貼的方便允許該行超過 80 字符.
- 包含長路徑的 `#include` 語句可以超出80列. 但應該盡量避免.
- [頭文件保護](#) 可以無視該原則.
## 8.2. 非 ASCII 字符
> Tip
> 盡量不使用非 ASCII 字符, 使用時必須使用 UTF-8 編碼.
即使是英文, 也不應將用戶界面的文本硬編碼到源代碼中, 因此非 ASCII 字符要少用. 特殊情況下可以適當包含此類字符. 如, 代碼分析外部數據文件時, 可以適當硬編碼數據文件中作為分隔符的非 ASCII 字符串; 更常見的是 (不需要本地化的) 單元測試代碼可能包含非 ASCII 字符串. 此類情況下, 應使用 UTF-8 編碼, 因為很多工具都可以理解和處理 UTF-8 編碼. 十六進制編碼也可以, 能增強可讀性的情況下尤其鼓勵 —— 比如 `"\xEF\xBB\xBF"` 在 Unicode 中是 _零寬度 無間斷_ 的間隔符號, 如果不用十六進制直接放在 UTF-8 格式的源文件中, 是看不到的. (yospaly 注: `"\xEF\xBB\xBF"` 通常用作 UTF-8 with BOM 編碼標記)
## 8.3. 空格還是制表位
> Tip
> 只使用空格, 每次縮進 2 個空格.
我們使用空格縮進. 不要在代碼中使用制符表. 你應該設置編輯器將制符表轉為空格.
## 8.4. 函數聲明與定義
> Tip
> 返回類型和函數名在同一行, 參數也盡量放在同一行.
函數看上去像這樣:
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
...
}
注意以下幾點:
>
> - 返回值總是和函數名在同一行;
> - 左圓括號總是和函數名在同一行;
> - 函數名和左圓括號間沒有空格;
> - 圓括號與參數間沒有空格;
> - 左大括號總在最后一個參數同一行的末尾處;
> - 右大括號總是單獨位于函數最后一行;
> - 右圓括號和左大括號間總是有一個空格;
> - 函數聲明和實現處的所有形參名稱必須保持一致;
> - 所有形參應盡可能對齊;
> - 缺省縮進為 2 個空格;
> - 換行后的參數保持 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*/) {}
Warning
// Bad - if someone wants to implement later, it's not clear what the
// variable means.
void Circle::Rotate(double) {}
## 8.5. 函數調用
> Tip
> 盡量放在同一行, 否則, 將實參封裝在圓括號中.
函數調用遵循如下形式:
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);
}
## 8.6. 條件語句
> Tip
> 傾向于不在圓括號內使用空格. 關鍵字 `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` 和左圓括號間都有個空格. 右圓括號和左大括號之間也要有個空格:
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();
通常, 單行語句不需要使用大括號, 如果你喜歡用也沒問題; 復雜的條件或循環語句用大括號可讀性會更好. 也有一些項目要求 `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;
}
## 8.7. 循環和開關選擇語句
> Tip
> `switch` 語句可以使用大括號分段. 空循環體應使用 `{}` 或 `continue`.
`switch` 語句中的 `case` 塊可以使用大括號也可以不用, 取決于你的個人喜好. 如果用的話, 要按照下文所述的方法.
如果有不滿足 `case` 條件的枚舉值, `switch` 應該總是包含一個 `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.
Warning
while (condition); // Bad - looks like part of do/while loop.
## 8.8. 指針和引用表達式
> Tip
> 句點或箭頭前后不要有空格. 指針/地址操作符 (`*, &`) 之后不能有空格.
下面是指針和引用表達式的正確使用范例:
x = *p;
p = &x;
x = r.y;
x = r->y;
注意:
- 在訪問成員時, 句點或箭頭前后沒有空格.
- 指針操作符 `*` 或 `&` 后沒有空格.
在聲明指針變量或參數時, 星號與類型或變量名緊挨都可以:
// 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 &
在單個文件內要保持風格一致, 所以, 如果是修改現有文件, 要遵照該文件的風格.
## 8.9. 布爾表達式
> Tip
> 如果一個布爾表達式超過 標準行寬, 斷行方式要統一一下.
下例中, 邏輯與 (`&&`) 操作符總位于行尾:
if (this_one_thing > this_other_thing &&
a_third_thing == a_fourth_thing &&
yet_another & last_one) {
...
}
注意, 上例的邏輯與 (`&&`) 操作符均位于行尾. 可以考慮額外插入圓括號, 合理使用的話對增強可讀性是很有幫助的.
## 8.10. 函數返回值
> Tip
> `return` 表達式中不要用圓括號包圍.
函數返回時不要使用圓括號:
return x; // not return(x);
## 8.11. 變量及數組初始化
> Tip
> 用 `=` 或 `()` 均可.
在二者中做出選擇; 下面的方式都是正確的:
int x = 3;
int x(3);
string name("Some Name");
string name = "Some Name";
## 8.12. 預處理指令
> 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();
}
## 8.13. 類格式
> 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);
};
注意事項:
- 所有基類名應在 80 列限制下盡量與子類名放在同一行.
- 關鍵詞 `public:`, `protected:`, `private:` 要縮進 1 個空格.
- 除第一個關鍵詞 (一般是 `public`) 外, 其他關鍵詞前要空一行. 如果類比較小的話也可以不空.
- 這些關鍵詞后不要保留空行.
- `public` 放在最前面, 然后是 `protected`, 最后是 `private`.
- 關于聲明順序的規則請參考 [聲明順序](#) 一節.
## 8.14. 初始化列表
> Tip
> 構造函數初始化列表放在同一行或按四格縮進并排幾行.
下面兩種初始化列表方式都可以接受:
> > > // 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();
...
}
## 8.15. 名字空間格式化
> Tip
> 名字空間內容不縮進.
[名字空間](#) 不要增加額外的縮進層次, 例如:
namespace {
void foo() { // Correct. No extra indentation within namespace.
...
}
} // namespace
不要縮進名字空間:
Warning
namespace {
// Wrong. Indented when it should not be.
void foo() {
...
}
} // namespace
## 8.16. 水平留白
> Tip
> 水平留白的使用因地制宜. 永遠不要在行尾添加沒意義的留白.
常規:
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.
...
添加冗余的留白會給其他人編輯時造成額外負擔. 因此, 行尾不要留空格. 如果確定一行代碼已經修改完畢, 將多余的空格去掉; 或者在專門清理空格時去掉(確信沒有其他人在處理). (yospaly 注: 現在大部分代碼編輯器稍加設置后, 都支持自動刪除行首/行尾空格, 如果不支持, 考慮換一款編輯器或 IDE)
循環和條件語句:
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 < <.
## 8.17. 垂直留白
> Tip
> 垂直留白越少越好.
這不僅僅是規則而是原則問題了: 不在萬不得已, 不要使用空行. 尤其是: 兩個函數定義之間的空行不要超過 2 行, 函數體首尾不要留空行, 函數體中也不要隨意添加空行.
基本原則是: 同一屏可以顯示的代碼越多, 越容易理解程序的控制流. 當然, 過于密集的代碼塊和過于疏松的代碼塊同樣難看, 取決于你的判斷. 但通常是垂直留白越少越好.
Warning
函數首尾不要有空行
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
}
## 譯者 (YuleFox) 筆記
1. 對于代碼格式, 因人, 系統而異各有優缺點, 但同一個項目中遵循同一標準還是有必要的;
1. 行寬原則上不超過 80 列, 把 22 寸的顯示屏都占完, 怎么也說不過去;
1. 盡量不使用非 ASCII 字符, 如果使用的話, 參考 UTF-8 格式 (尤其是 UNIX/Linux 下, Windows 下可以考慮寬字符), 盡量不將字符串常量耦合到代碼中, 比如獨立出資源文件, 這不僅僅是風格問題了;
1. UNIX/Linux 下無條件使用空格, MSVC 的話使用 Tab 也無可厚非;
1. 函數參數, 邏輯條件, 初始化列表: 要么所有參數和函數名放在同一行, 要么所有參數并排分行;
1. 除函數定義的左大括號可以置于行首外, 包括函數/類/結構體/枚舉聲明, 各種語句的左大括號置于行尾, 所有右大括號獨立成行;
1. `.`/`->` 操作符前后不留空格, `*`/`&` 不要前后都留, 一個就可, 靠左靠右依各人喜好;
1. 預處理指令/命名空間不使用額外縮進, 類/結構體/枚舉/函數/語句使用縮進;
1. 初始化用 `=` 還是 `()` 依個人喜好, 統一就好;
1. `return` 不要加 `()`;
1. 水平/垂直留白不要濫用, 怎么易讀怎么來.
1. 關于 UNIX/Linux 風格為什么要把左大括號置于行尾 (`.cc` 文件的函數實現處, 左大括號位于行首), 我的理解是代碼看上去比較簡約, 想想行首除了函數體被一對大括號封在一起之外, 只有右大括號的代碼看上去確實也舒服; Windows 風格將左大括號置于行首的優點是匹配情況一目了然.
- Google 開源項目風格指南 (中文版)
- C++ 風格指南
- 0. 扉頁
- 1. 頭文件
- 2. 作用域
- 3. 類
- 4. 來自 Google 的奇技
- 5. 其他 C++ 特性
- 6. 命名約定
- 7. 注釋
- 8. 格式
- 9. 規則特例
- 10. 結束語
- Objective-C 風格指南
- Google Objective-C Style Guide 中文版
- 留白和格式
- 命名
- 注釋
- Cocoa 和 Objective-C 特性
- Cocoa 模式
- Python 風格指南
- Google Python 風格指南 - 中文版
- 背景
- Python語言規范
- Python風格規范
- 臨別贈言
- JSON 風格指南
- 簡介
- 定義
- 一般準則
- 屬性名準則
- 屬性值準則
- 屬性值數據類型
- JSON結構和保留屬性名
- 頂級保留屬性名稱
- data對象的保留屬性名
- 用于分頁的保留屬性名
- 用于鏈接的保留屬性名
- 錯誤對象中的保留屬性名
- 屬性順序
- 示例
- 附錄