C++ 常量学习笔记
在 C++ 中,常量是指不能被修改的值。常量可以是字面值,也可以由程序员定义。
字面值常量
字面值常量是指程序中直接出现在代码中的值。例如:
cppCopy Codeint age = 18; // 18 就是一个字面值常量
double pi = 3.14159; // 3.14159 就是一个字面值常量
const 关键字
在 C++ 中,我们使用 const
关键字来定义常量。例如:
cppCopy Codeconst int MAX = 100;
const double PI = 3.14159;
const
关键字告诉编译器,这个变量是一个常量,不能被修改。尝试修改一个常量会导致编译错误。
cppCopy Codeconst int MAX = 100;
MAX = 200; // 编译错误:assignment of read-only variable ‘MAX’
constexpr 关键字
C++11 引入了 constexpr
关键字,用于定义在编译时就可以计算出结果的常量表达式。
cppCopy Codeconstexpr int square(int x) {
return x * x;
}
const int a = square(5); // a 的值在编译时就计算出来了,等于 25
实例
下面是一些常量的实例:
cppCopy Codeconst int MAX_SIZE = 100;
const double PI = 3.14159;
const char NEWLINE = '\n';
constexpr int square(int x) {
return x * x;
}
const int a = square(5); // 等于 25
在实际编程中,定义常量可以使代码更加易读易维护。例如,如果我们需要在程序中多次使用一个固定的值,那么将其定义为常量可以避免拼写错误和代码重复。
cppCopy Codeconst int MAX_SIZE = 100;
int main() {
int arr[MAX_SIZE];
// do something
return 0;
}
以上就是 C++ 常量的学习笔记。