【C++】定义常量
在 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
请注意,把常量定义为大写字母形式,是一个很好的编程实践。