第六章 語句 statements
一般語句是順序執行的。控制流語句,允許又提案件的執行或者重複執行部分功能。
if、switch語句爲條件分支結構
for、while、do while是循環迭代語句
6.2 表達式語句以分號結束,空語句(null statements) ;(單獨一個分號作爲一個程序語句)
while (cin >> s && s != sought)
; // null statement 最好加上註釋能夠知道該語句是有意省略的
6.3 複合語句(compound statements)塊語句是用一對花括號成立的
6.4 語句作用域
// index is visible only within the for statement
for (vector<int>::size_type index = 0;
index != vec.size(); ++index)
{ // new scope, nested within the scope of this for statement
int square = 0;
if (index % 2) // ok: index is in scope
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // error: index is not visible here
在控制結構裏引入的名字是該語句的局部變量,其作用域侷限在語句內部。
// index is visible only within the for statement
for (vector<int>::size_type index = 0;
index != vec.size(); ++index)
{ // new scope, nested within the scope of this for statement
int square = 0;
if (index % 2) // ok: index is in scope
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // error: index is not visible here
如果程序需要訪問某個控制結構中的變量,那麼這個變量必須在控制語句外部定義。
6.5 if語句
當多個語句必須作爲單個語句執行時,比較常見的錯誤是漏掉了花括號。
懸垂else問題:所有語言的 if 語句都普通存在着潛在的二義性。C++ 中懸垂 else 問題帶來的二義性,通過將 else 匹配給最後出現的尚未匹配的 if 子句來解決,可以通過用花括號將內層的 if 語句括起來成爲複合語句,從而迫使這個 else 子句與外層的 if 匹配。
6.6 switch語句
char ch;
// initialize counters for each vowel
int aCnt = 0, eCnt = 0, iCnt = 0,
oCnt = 0, uCnt = 0;
while (cin >> ch) {
// if ch is a vowel, increment the appropriate counter
switch (ch) {
case 'a':
++aCnt;
break;
case 'e':
++eCnt;
break;
case 'i':
++iCnt;
break;
case 'o':
++oCnt;
break;
case 'u':
++uCnt;
break;
}
}
// print results
cout << "Number of vowel a: \t" << aCnt << '\n'
<< "Number of vowel e: \t" << eCnt << '\n'
<< "Number of vowel i: \t" << iCnt << '\n'
<< "Number of vowel o: \t" << oCnt << '\n'
<< "Number of vowel u: \t" << uCnt << endl;
關鍵字case和所關聯的值稱爲case標號,case標號必須是整型常量表達式
儘管沒有嚴格要求在 switch 結構的最後一個標號之後指定 break 語句,但是,爲了安全起見,最好在每個標號後面提供一個 break 語句,即使是最後一個標號也一樣。如果以後在 switch 結構的末尾又需要添加一個新的 case 標號,則不用再在前面加 break 語句了。
case 'a': case 'A': 寫成case 'a', 'A':
6.7 while語句