在C++中,constexpr
和const
都用于定义常量,但它们有着不同的用途和行为。以下是详细讲解以及相应实例代码。
#include <iostream>
int main() {
const int constantValue = 10;
// const 变量在运行时确定值,不能修改
// 在编译时期无法进行计算
int array[constantValue];
// 下面的语句是非法的,因为 constantValue 是在运行时确定的
// const int anotherValue = constantValue + 5;
std::cout << constantValue << std::endl;
return 0;
}
#include <iostream>
constexpr int ComputeValue(int x) {
// constexpr 函数在编译时期进行计算
return x * 2;
}
int main() {
constexpr int constantValue = ComputeValue(5);
// constexpr 变量在编译时期确定值
// 可以用于数组大小、枚举等需要在编译时期确定的地方
int array[constantValue];
// constexpr 函数返回值可以在编译时期确定
constexpr int computedValue = ComputeValue(3);
std::cout << constantValue << std::endl;
std::cout << computedValue << std::endl;
return 0;
}
const: 用于定义在运行时期确定值的常量,适用于各种常量,但无法用于在编译时期确定值的计算。
constexpr: 用于定义在编译时期确定值的常量,适用于需要在编译时期计算的场景,如数组大小、枚举值等。
const
用于运行时期常量,而constexpr
则强调在编译时期常量,并提供更多的编译期计算能力。