
C++ 速查手冊
13.5 - 常數
關鍵字 const 用來定義常數 (constant) ,凡是以 const 宣告後的變數設定初值後,都不能重新指派新的值,例如
#include <iostream>
int main() {
const int a = 22;
std::cout << "a: " << a << std::endl;
a = 1;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u1305_1.cpp
功能:示範 C++ 的其他宣告
作者:張凱慶*/
此例宣告 a 為常數並且設定初值為 22
const int a = 22;
下面重新設定 a 的值
a = 1;
這樣並不會通過編譯
| $ g++ u1305_1.cpp |
| u1305_1.cpp:7:7: error: cannot assign to variable 'a' with const-qualified type |
| 'const int' |
| a = 1; |
| ~ ^ |
| u1305_1.cpp:4:15: note: variable 'a' declared const here |
| const int a = 22; |
| ~~~~~~~~~~^~~~~~ |
| 1 error generated. |
| $ |
常數通常可使程式語意更清楚,例如
#include <iostream>
int main() {
const int End = 0;
for (int i = 10; i > End; i--) {
std::cout << i << std::endl;
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://kaiching.org/
檔名:u1305_2.cpp
功能:示範 C++ 的其他宣告
作者:張凱慶*/
這裡先定義一個常數 End
const int End = 0;
End 就是迴圈 (loop) 結束的條件,這樣語意就清楚多了
for (int i = 10; i > End; i--) {
條件控制的地方也可以用變數,但是如果在程式中其他地方不小心更動到變數的值,迴圈結果就很難預期了。
編譯執行結果如下
| $ g++ u1305_2.cpp |
| $ python3 high.py u1305_2.cpp |
| $ ./a.out |
| 10 |
| 9 |
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 1 |
| $ |
