在C++中,const和constexpr都和常量有关,但语义和使用场景并不一样。const侧重于告诉编译器该对象不可被修改,而constexpr则强调值必须在编译期就能确定。理解这两者的区别,有助于写出更安全且高效的代码。

const与constexpr的基本语义
const用来声明一个只读对象,它在运行期不能被修改,但不要求初始值在编译期已知。例如从配置文件读入的值可以定义为const,但无法作为数组长度。
constexpr用于声明编译期常量或编译期函数,要求表达式在编译时完成求值。它既能修饰变量,也能修饰函数。
主要区别对比
| 特性 | const | constexpr |
|---|---|---|
| 求值时机 | 运行期或编译期 | 必须是编译期 |
| 能否作数组大小 | 不一定 | 可以 |
| 函数修饰 | 不支持 | 支持编译期函数 |
| 修改限制 | 运行期只读 | 编译期确定且只读 |
代码示例说明
下面通过一段C++代码展示两者在变量定义上的差异:
#include <iostream>
int getValue() {
return 10; // 运行期才能确定
}
int main() {
const int a = getValue(); // 合法,运行时常量
// int arr1[a]; // 错误,a不是编译期常量
constexpr int b = 20; // 编译期常量
int arr2[b]; // 合法,b可用于数组大小
constexpr int c = getValue(); // 错误,getValue不是constexpr函数
std::cout << a << b << std::endl;
return 0;
}
constexpr函数
使用constexpr修饰的函数,若传入编译期常量参数,则在编译期求值;否则退化为运行期函数。
constexpr int square(int x) {
return x * x; // 简单返回,可编译期求值
}
int main() {
constexpr int s = square(5); // 编译期算出25
int y = 3;
int r = square(y); // 运行期调用
return 0;
}
如何选择
- 若值来自运行期输入且只需只读保护,用const。
- 若值编译期已知且需用于数组、模板参数等,用constexpr。
- 对性能敏感且可编译期计算的场景,优先constexpr。
简单记:const是只读标签,constexpr是编译期计算标签。
constconstexprcompile_time_constant修改时间:2026-07-26 01:54:18