在 C++ 中,有兩種簡單的定義常量的方式:
- 使用
#define
預處理器。 - 使用
const
關鍵字。
#define 預處理器
#include <iostream>
using namespace std;#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'int main()
{int area; area = LENGTH * WIDTH;cout << area;cout << NEWLINE;return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
50
const 關鍵字
#include <iostream>
using namespace std;int main()
{const int LENGTH = 10;const int WIDTH = 5;const char NEWLINE = '\n';int area; area = LENGTH * WIDTH;cout << area;cout << NEWLINE;return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
50
請注意,把常量定義為大寫字母形式,是一個很好的編程實踐。