Statement
-
Compound Statements (Blocks)
在 { } 中間一連串的 statements 或 declarations (也允許是空的),且不用 ; 作為中止符。
while (val <= 10) {
sum += val;
++val;
}
-
Conditional Statements
有 if statement, if else statement 和 switch statement。以下面的 switch code 為示範,"switch (ch)" 的 ch 為 expression,"case 'a':", "case 'e':" ... 為 case label,當 expression match case label,execution 就會從此開始直到 switch 的中止符或 break,所以是有可能橫跨 case labels。合法 case label 為 integral constant expressions,也就是 integral type 的 constant expression。
int vowelCnt = 0
while (cin >> ch) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
++vowelCnt;
break;
}
}
-
Why can't variables be declared in a switch statement?
首先這是 stackoverflow 裡的一個問題,問題題目應該改成 Why can't variables be initialized in a switch statement?,因為如果只有 declared 是合法的,頂多有 warning。基本上 case 就是 label 的一種,一種常見於有 goto 的程式碼。若你做 variable definition 在 switch statement,等於在這 switch statement scope 裡會有機會因為做了 goto label 的關係而忽略掉該 definition,進而導致程式碼出錯。若要在 switch statement 做 variable definition,你就必須很明確地告訴 compiler 即使有 goto label 忽略該 variable definition 也沒差,因為我只會在那 case 裡使用,也就是加 {} 更近一步明確地縮小 variable definition 的 scope 而非整個 switch statement scope。(Declaration跟Definition間的差異)
switch (num) {
case 1:
int init = 0;
cout << declare << endl;
}
switch (num) {
case 1:
int init = 0;
cout << init << endl;
case 2:
cout << 9999 << endl;
}
switch (num) {
case 1:
{
int init = 0;
cout << init << endl;
}
case 2:
cout << 9999 << endl;
}
int num = 2;
switch (num) {
case 1:
int declare;
declare = 5;
case 2:
cout << declare << endl;
}
-
Iterative Statements
有 while statement, for statement 跟 do while Statement。C++ 的 for statement 除了傳統的還有 range for statement。其中 expression 必須要是 braced initializer list, array, vector 或 string 其中一種。
for (declaration : expression)
statement
參考資料 :
1.why-cant-variables-be-declared-in-a-switch-statement
0 意見:
張貼留言