開始學習第六章《語句》
1、簡單語句
空語句
;
只有一個分號。在某些條件下使用,如從輸入流讀入數據,而不需操作:
while (cin >> s && s != "abc")
; // null statement
使用空語句時最好加上注釋
a = b + 1;;
看似非法的分號,其實是一個空語句。但并不意味著就能隨便使用,如
while (iter != vec.end()) ; // while循環體為空
++iter; // 不是循環體的一部分
會無限循環。
復合語句(塊)
用花括號括起來的語句序列(也可能為空)。如 for 和 while
while (cin >> trans)
if (total.same_isbn(trans))
total = total + trans;
else {
cout << total << endl;
total = trans;
}
else
分支需要用塊語句。
塊語句并不是以分號結束
也可以是 空塊
while (cin >> s && s != "abc")
{} // 空塊
語句作用域
while (int i = get_num())
cout << i << endl;
i = 0; // error
i
超出了作用域。
控制結構中引入的變量是局部變量,僅在塊語句結束前有效。
for (vector<int>::size_type index = 0;
index != vec.size(); ++index)
{
int square = 0;
if (index % 2)
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // error
如果要在控制語句外訪問,則需定義在控制語句外
vector<int>::size_type index = 0
for (; index != vec.size(); ++index)
{
int square = 0;
if (index % 2)
square = index * index;
vec[index] = square;
}
if (index != vec.size()) // ok
2、if語句
if語句
if (condition1)
{
statement1
}
else if (condition2)
{
staement2
}
else
{
staement3
}
目前為止,除了 vector 和 string 類型一般不可作為條件外,均可作為if語句的條件,包括 IO 類型。
各分支語句用
{}
括起來是一個好的習慣
if語句可以嵌套
例如,
if (condition1)
{
if (condition2)
{
statement1
}
else
{
staement2
}
}
else
{
// use if statement here also valid
staement3
}
END.