常量表達式是指值不會改變並且在編譯時就能得到計算結果的表達式。比如字面值和用常量表達式初始化的const對象。
const int max = 20;
const int max_1 = max + 1;
而如下對象則不是常量表達式:
int staff = 5;
const int sz = get_size();
constexpr變量
C++11規定允許將變量聲明爲constexpr類型以便由便一起來驗證變量的值是否是一個常量表達式。聲明爲constexpr的變量一定是一個常量而且必須由常量表達式初始化:
constexpr int mf = 20;
constexpr int limit = mf + 1;
constexpr int sz = size(1); // 編譯錯誤
常量和constexpr
使用constexpr關鍵字定義指針時,constexpr只對指針有效,對指針所知的對象無關:
const int *p = nullptr; // p是一個指向整型常量的指針
constexpr int *q = nullptr; // q是一個指向整型變量的常量指針
constexprt指針既可以指向常量也可以指向非常量:
const int *p = nullptr; // p是一個指向整型常量的指針
constexpr int *q = nullptr; // q是一個指向整型變量的常量指針
constexpr int *np = nullptr; // np是一個指向整數的常量指針
int j = 0;
constexpr int i = 42; // 常量i
constexpr const int *p1 = &i; // p1是一個指向常量i的常量指針
constexpr int *p2 = &j; // p2是一個指向變量j的常量指針