編寫代碼時(shí),您的首要任務(wù)應(yīng)該是可讀性。大量時(shí)間花在調(diào)試和維護(hù)代碼上,通常遠(yuǎn)遠(yuǎn)超過最初編寫代碼所花費(fèi)的時(shí)間。因此,使該過程高效是必不可少的。考慮到未來人類讀者的需求(可能是你,當(dāng)然!)比試圖讓代碼“高效”更重要——這項(xiàng)工作主要可以留給現(xiàn)代編譯器。
這種考慮意味著代碼應(yīng)該非常仔細(xì)地格式化和對(duì)齊,并且語言結(jié)構(gòu)應(yīng)該盡可能簡(jiǎn)單和透明。有許多已發(fā)布的指南可以幫助解決這些問題。但是,創(chuàng)建可讀代碼并不止于此。
當(dāng)你編譯代碼時(shí),編程語言被翻譯成機(jī)器指令。這是顯而易見的。然而,編譯器實(shí)際接收的是一個(gè)字符流;有些是實(shí)際代碼,但可能有一些不打算翻譯的塊,其他文本可能僅供人類使用:
文檔——代碼中的注釋
臨時(shí)刪除的代碼——調(diào)試過程的一部分,但它可能會(huì)持續(xù)存在
特殊調(diào)試/跟蹤代碼
每一個(gè)的實(shí)現(xiàn)都會(huì)對(duì)可讀性產(chǎn)生一些影響。
文檔
每個(gè)人都知道評(píng)論是個(gè)好主意,但我們大多數(shù)人都很懶惰。但是,一些努力是非常值得的。舊式/*.。.*/注釋符號(hào)是可以接受的,但新的行尾//。..形式更清晰。仍然需要護(hù)理。例如:
int number; // input count
char c; // single character buffer
char buffer[99]; // the input line
很難跟上。對(duì)齊就是一切:
int number; // input count
char c; // single character buffer
char buffer[99]; // the input line
并且不要使用標(biāo)簽;它們不是便攜式的。
臨時(shí)代碼刪除
在軟件開發(fā)過程中,想要對(duì)編譯器“隱藏”部分代碼——將其關(guān)閉——并不少見。執(zhí)行此操作的傳統(tǒng)方法是“注釋掉”——在代碼前加/* ,在后加*/。雖然做起來很快,但它很容易失效,因?yàn)榫幾g器不一定支持注釋嵌套。較新的//表示法稍微好一點(diǎn),但應(yīng)用和刪除很繁瑣,并且仍然容易出錯(cuò)。
實(shí)現(xiàn)此結(jié)果的最佳方法是使用預(yù)處理器指令,因此:
#if 0
#endif
Debug/Trace code
A particular kind of temporarily visible code is instrumentation – extra code added for debugging and/or tracing. Although modern debuggers and tracing tools can do a remarkable job, sometimes instrumenting the code is the only way to glean visibility and figure out exactly what is happening.
The usual way to accommodate this need is using pre-processor directives, as before, but using a symbol to switch them on and off:
#ifdef DEBUG_TRACE
#endif
So, when the symbol DEBUG_TRACE is defined, the debug code is included.
A slightly different approach is to code it like this:
#ifndef NDEBUG
#endif
Although this double negative does seem confusing, some consistency is introduced, as this symbol is used to enable the standard assert() macro. The symbol needs to be defined to suppress debug mode.
審核編輯:郭婷
-
處理器
+關(guān)注
關(guān)注
68文章
19833瀏覽量
233892 -
編譯器
+關(guān)注
關(guān)注
1文章
1657瀏覽量
49968
發(fā)布評(píng)論請(qǐng)先 登錄
評(píng)論