Chapter 7: Centralized exiting of functions
第7章: 函式的集中離開
Albeit deprecated by some people, the equivalent of the goto statement is used frequently by compilers in form of the unconditional jump instruction.
雖然有些人反對,但是事實上編譯器仍然在以無條件跳躍指令的形式使用goto語句。
The goto statement comes in handy when a function exits from multiple locations and some common work such as cleanup has to be done.
當函式需要從多個位置退出,並且需要做一些通用的清理工作時,goto語句就顯得很方便。
The rationale is:
使用goto有以下的原因:
- unconditional statements are easier to understand and follow
- nesting is reduced
- errors by not updating individual exit points when making modifications are prevented
- saves the compiler work to optimize redundant code away ;)
- 無條件跳躍指令是更容易理解和跟蹤
- 減少了程式碼的巢狀
- 防止修改代碼時因為沒有更新某個退出點而產生的錯誤
- 減少了編譯器最佳化多餘程式碼的工作量 ;)
int fun(int a)
{
int result = 0;
char *buffer = kmalloc(SIZE);
if (buffer == NULL)
return -ENOMEM;
if (condition1) {
while (loop1) {
...
}
result = 1;
goto out;
}
...
out:
kfree(buffer);
return result;
}
Chapter 8: Commenting
第8章: 註解
Comments are good, but there is also a danger of over-commenting. NEVER try to explain HOW your code works in a comment: it's much better to write the code so that the _working_ is obvious, and it's a waste of time to explain badly written code.
註解是件好事,但是也有過分註解的危險。絕對不要在註解內試著解釋你的碼是如何工作的: 這還不如把程式寫得清楚點,一看就知道它在幹麻,而且解釋一段亂寫的碼是件浪費時間的事。
Generally, you want your comments to tell WHAT your code does, not HOW. Also, try to avoid putting comments inside a function body: if the function is so complex that you need to separately comment parts of it, you should probably go back to chapter 6 for a while. You can make small comments to note or warn about something particularly clever (or ugly), but try to avoid excess. Instead, put the comments at the head of the function, telling people what it does, and possibly WHY it does it.
大致而言,你要你的註解說明你的程式做了什麼,而不是如何做。並且,試著避免在函式裡面放注釋:如果你的程式複雜到需要對部份的內容做註解,你可能需要再花點時間重看第6章。你可以放些小註解來解釋或警告一些特別的小聰明 (或醜陋的) 地方,但是儘量避免過分使用。正確的作法應是把註解放在函式開頭的地方,告訴他人它要作什麼,可能還要說明為什麼要做這些事。
When commenting the kernel API functions, please use the kernel-doc format. See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc for details.
Linux style for comments is the C89 "/* ... */" style.
Don't use C99-style "// ..." comments.
The preferred style for long (multi-line) comments is:
/*
* This is the preferred style for multi-line
* comments in the Linux kernel source code.
* Please use it consistently.
*
* Description: A column of asterisks on the left side,
* with beginning and ending almost-blank lines.
*/
It's also important to comment data, whether they are basic types or derived types. To this end, use just one data declaration per line (no commas for multiple data declarations). This leaves you room for a small comment on each item, explaining its use.
留言列表