C++ Primer 之 讀書筆記 第六章
switch
switch語句我用的的確不多,還是習(xí)慣寫成if-else的形式。
switch 中的控制流:
It is a common misunderstanding to expect that only the statements associated with the matched case label are executed. However, execution continues across case boundaries until the end of the switch statement or a break is encountered. 存在一個普遍的誤解:以為程序只會執(zhí)行匹配的 case 標(biāo)號相關(guān)聯(lián)的語句。實際上,程序從該點開始執(zhí)行,并跨越 case 邊界繼續(xù)執(zhí)行其他語句,直到 switch 結(jié)束或遇到 break 語句為止。 |
有2種switch常見的錯誤寫法:
l case 標(biāo)號必須是整型常量表達式。
l 如果兩個 case 標(biāo)號具有相同的值,同樣也會導(dǎo)致編譯時的錯誤。
Switch內(nèi)部的變量定義:
對于 switch 結(jié)構(gòu),只能在它的最后一個 case 標(biāo)號或 default 標(biāo)號后面定義變量。
do while語句
用作條件判斷的變量一定要定義在循環(huán)體之外,
// repeatedly ask user for pair of numbers to sum string rsp; // used in the condition; can't be defined inside the do do { // ... } while (!rsp.empty() && rsp[0] != 'n'); |
do while 循環(huán)不可以采用如下方式定義變量:
// error: declaration statement within do condition is not supported do { // ... mumble(foo); } while (int foo = get_foo()); // error: declaration in do condition |
不過其實自己寫代碼時,這個各色的寫法一般是不會出現(xiàn)的。
Using the Preprocessor for Debugging(使用預(yù)處理器進行調(diào)試)
預(yù)處理器還定義了其余四種在調(diào)試時非常有用的常量:
__FILE__ 文件名
__LINE__ 當(dāng)前行號
__TIME__ 文件被編譯的時間
__DATE__ 文件被編譯的日期
斷言assert是一種預(yù)處理宏,assert 宏就求解條件表達式,如果結(jié)果為 false,assert 輸出信息并且終止程序的執(zhí)行。如果該表達式有一個非零(例如,true)值,則 assert 不做任何操作。
posted on 2009-05-20 14:21 amenglai 閱讀(235) 評論(0) 編輯 收藏 所屬分類: C++ Primer 之 讀書筆記