C 語言的語法對縮進和空白並無強制要求,開發者可以隨意使用空格、Tab 或換行。同樣功能的程式碼,寫得整潔易讀,也能寫得雜亂難懂。良好的編碼風格不僅提升可讀性,更能降低維護成本,避免因排版混亂導致的邏輯錯誤。
以下程式碼省略所有空白與縮進,雖然能編譯執行,但極難閱讀:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
char gesture[3][10]={"scissor","stone","cloth"};
int man,computer,result, ret;
srand(time(NULL));
while(1){
computer=rand()%3;
printf("\nInput your gesture (0-scissor 1-stone 2-cloth):\n");
ret=scanf("%d",&man);
if(ret!=1||man<0||man>2){
printf("Invalid input!\n");
return 1;
}
printf("Your gesture: %s\tComputer's gesture: %s\n",gesture[man],gesture[computer]);
result=(man-computer+4)%3-1;
if(result>0)printf("You win!\n");
else if(result==0)printf("Draw!\n");
else printf("You lose!\n");
}
return 0;
}
此類程式碼密度過高,缺乏視覺層次,一旦超過一畫面便幾乎無法維護。
雖然 [CodingStyle] 未強制規定空白細節,但主流 C 風格指南大同小異,核心原則如下:
if (cond)、while (1)、for (i=0; i<10; i++)。括號內表達式緊貼括號,如 (i<10)。i = i + 1、x < 1、a & b。單目運算符與操作數間不加空格:++i、!flag、-x、&a[1]。s.a、函式呼叫 foo(arg)、陣列索引 a[i]。for (i=1; i<10; i++)、foo(arg1, arg2)。distance = sqrt(x*x + y*y),但絕不可誤導閱讀者(例:a||b && c 易被誤解)。if (sqrt(x*x + y*y) > 5.0
&& x < 0.0
&& y > 0.0)
printf("This is such a long sentence that "
"it cannot be held within a line\n");
int a, b;
double c;
核心風格要求只能用 Tab 字元縮進,不可用空格代替。標準終端下一個 Tab 寬度為 8 格,建議編輯器也設為 8 格,如此大縮進能清晰呈現程式碼層次。混用空格與 Tab 會導致調整 Tab 寬度時排版崩潰。
if/else、while、do/while、for、switch 等帶區塊的語句,左大括號 { 與關鍵字同行,中間以空格分隔;右大括號 } 獨佔一行,並與對應關鍵字對齊:
if (...) {
陳述句列表
} else if (...) {
陳述句列表
}
此風格與 K&R 一致,優點是節省行數,一畫面能顯示更多程式碼。另一種常見風格將左大括號單獨置於下一行,兩者皆廣泛使用,專案內部保持一致即可。
與控制語句不同,函式定義的 { 與 } 各佔一行:
int foo(int a, int b)
{
陳述句列表
}
switch 區塊內的 case、default 標籤與 switch 關鍵字同縮進層級,標籤下的陳述句再縮進一層:
switch (c) {
case 'A':
陳述句列表
case 'B':
陳述句列表
default:
陳述句列表
}
供 goto 使用的自訂標籤應頂格書寫,不縮進。
return 前)。#include <stdio.h>
#include <stdlib.h>
int g;
double h;
int foo(void)
{
陳述句列表
}
int bar(int a)
{
陳述句列表
}
int main(void)
{
int a, b;
double c;
陳述句組1
陳述句組2
return 0;
}
統一的編碼風格是團隊協作的基石。無論採用哪種具體規範,核心在於一致性與可讀性。建立專案風格指南,並配合編輯器自動格式化工具(如 clang-format),能有效降低風格爭議,讓團隊專注於邏輯本身。