
關鍵字 const 用來定義常數 (constant) ,凡是以 const 宣告後的變數設定初值後,都不能重新指派新的值,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | const int a = 22; |
| 005 | std::cout << "a: " |
| 006 | << a |
| 007 | << std::endl; |
| 008 | |
| 009 | a = 1; |
| 010 | |
| 011 | return 0; |
| 012 | } |
| 013 | |
| 014 | /* Kaiching Chang |
| 015 | u1305_1.cpp |
| 016 | 2014-02 */ |
此例宣告 a 為常數並且設定初值為 22
| 004 | const int a = 22; |
下面重新設定 a 的值
| 009 | a = 1; |
這樣並不會通過編譯
| $ g++ u1305_1.cpp |
| u1305_1.cpp:9:6: error: read-only variable is not assignable |
| a = 1; |
| ~ ^ |
| 1 error generated. |
| $ |
常數通常可使程式語意更清楚,例如
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | const int End = 0; |
| 005 | for (int i = 10; i > End; i--) { |
| 006 | std::cout << i |
| 007 | << std::endl; |
| 008 | } |
| 009 | |
| 010 | return 0; |
| 011 | } |
| 012 | |
| 013 | /* Kaiching Chang |
| 014 | u1305_2.cpp |
| 015 | 2014-02 */ |
這裡先定義一個常數 End
| 004 | const int End = 0; |
End 就是迴圈 (loop) 結束的條件,這樣語意就清楚多了
| 005 | 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 |
| $ |
continue ...
沒有留言:
張貼留言