Const Expression in c++

  • const: meaning roughly “I promise not to change this value.” This is used primarily to specify interfaces so that data can be passed to functions using pointers and references without fear of it being modified. The compiler enforces the promise made by const. The value of a const can be calculated at runtime.

  • constexpr: meaning roughly “to be evaluated at compile time.” This is used primarily to specify constants, to allow placement of data in read-only memory (where it is unlikely to be corrupted), and for performance. The value of a constexpr must be calculated by the compiler.

int times2(int a){
    return a*2;

constexpr int times2_c(int a){
    return a*2;

// constexpr function can also be used for non-constant arguments;
// constexpr function should be simple and should not modify non-local variables;

// this is (supposed to be) a constexpr function 
// but not implemented with the declaration.
constexpr int times2_c2(int a); 

int main(){
    // using constant expression is ok.
    const int c1 = 10;
    constexpr int c_expr1 = 11;

    // using another const is ok.
    const int c2 = c1 + 2;
    constexpr int c_expr2 = c1+2;

    // const can be calculated at runtime, constexpr can not.
    const int c3 = times2(c2);
    const int c4 = times2(c2);

    constexpr int c_expr3 = times2(1); // this is an error
    constexpr int c_expr4 = times2(c2); // this is an error

    // using a constant expr function: 
    int v = 1;
    const int c5 = times2_c(1);
    const int c6 = times2_c(c2);
    constexpr int c_expr5 = times2_c(1);  // this is ok.
    constexpr int c_expr6 = times2_c(c2); // this is ok, because both times2_c and c2 are constant expr
    constexpr int c_expr7 = times2_c(v);  // this is an error, because v is not constant

    // using a constexpr function, but not implemented at the beginning
    const int c7 = times2_c2(1);
    constexpr int c_expr8 = times2_c2(1); // this is an error.

    return 0;

constexpr int times2_c2(int a){
    return a*2;

ref: A tour of C++