/* 控制語句:左大括號行尾,右大括號行首 */
if (x == y) {
do_something();
} else if (x > y) {
do_other();
} else {
do_default();
}
/* 函數定義:左大括號獨佔下一行行首 */
int function(int x) {
body_of_function;
}
/* do-while 特例:右大括號後接 while */
do {
body;
} while (condition);
原則:K&R 風格減少空行,騰出空間寫註釋;函數特殊對待因其可見性更高。
i,臨時值用 tmp。無需 loop_counter 這樣冗長名字。count_active_users() 而非 cntusr()。作用域越大,名字越具體。dwLength)屬於「腦子有毛病」——編譯器已檢查類型,命名混淆視覺。MAX_BUFFER_SIZE。/* FIXME: */、/* HACK: */ 供後續重構。indent 可自動格式化,但需正確參數:
indent -kr -i8 -ts8 -sob -l80 -bad -bap -nbc -br -brs -ncdb -nce -npcs -nprs -npsl -saf -sai -saw -ncs -nbfda -cp1 -cli0 -cbi0 -cdw -nss -l120 *.c
關鍵參數:-kr (K&R)、-i8 (縮進 8)、-ts8 (Tab 寬 8)。
Emacs 用戶加入 .emacs:
(defun linux-c-mode()
"C mode with adjusted defaults for Linux kernel."
(interactive)
(c-mode)
(c-set-style "K&R")
(setq c-basic-offset 8))
(setq auto-mode-alist
(cons '("/usr/src/linux/.*\\.[ch]$" . linux-c-mode) auto-mode-alist))
統一風格降低認知負荷,便於團隊協作與代碼審查。**工具自動化執行風格,人專注業務邏輯。**