C++ 编译时常量 与 运行时常量

29 阅读1分钟

编译时常量是真正的常量,而运行时常量是常变量。区分一个数据时真常量还是常变量,取决于const修饰的变量本身是不是能在编译期确定。const的完整英文是constant.

const修饰的变量,一般统称为常变量。具体来看,

  • 如果const修饰的变量是可以在编译期间确定,那就是真常量;
  • 如果const用来修饰一个需要用户输入,函数返回,动态计算等情况,要在运行期间才能确定,那就是常变量。

// 1. constexpr 编译时常量(C++11+)
constexpr int MAX_SIZE = 100; // 编译期确定值,无运行时内存
int arr[MAX_SIZE]; // 合法:编译时常量可用于数组大小
//====================================================
constexpr int a_expr = 20; //编译时常量。a_expr是编译时常量。
constexpr int b_expr = a_expr + 15; //编译时常量。b_expr在编译期可计算。

// 2. 枚举常量(天然编译时常量)
enum class Color { Red = 1, Green = 2 };

// 3. 编译期函数(constexpr 函数)
constexpr int add(int a, int b) {
    return a + b;
}
// 4. const修饰的编译时常量
const int a = 10; // a 是真变量。

//————————————————————————
// 对于运行阶段才能得到的数据,即便用const修饰了,那也是运行时常量,即常变量。
#include <iostream>
using namespace std;

int main () {
    string input_msg;
    cin >> input_msg;
    cout << input_msg << endl;
    return 0;
}

const 规范的是修改权限,即能不能写数据。编译时常量 规范的是 取值何时确定。

模板参数必须是编译时常量。