Constexpr syntax has been supported since C++ 11, so be careful to configure the compilation environment to support the standard version. For example, compile with g++. Add -std=c++11.

The following is an example command

g++ -std=c++11 main.cpp
Copy the code

Of course you can choose a higher version to compile, after all forward compatibility, such as -std=c++2a.

In C++, the semantics of const are read-only attributes used to modify a variable or member function. Such as:

const int a = 100;
Copy the code

So, semantically, const does not represent a compile-time constant. To take advantage of C++ templating techniques and optimize as much code as possible at compile time, C++11 introduced constexpr, which modifies a compile-time constant.

In some cases constEXPr and const are used in the same way.

const int a = 100;
constexpr int b = 100;
std::array<int, a> arr1;
std::array<int, b> arr2;
Copy the code

Constexpr, however, has an even more important role in modifying functions. When a function is modified by constExpr, the compiler optimizes it as follows: When a function is called, the compiler replaces the result as a compile-time constant if the result can be determined at compile time, otherwise it is called as a run-time function.

Here’s an example:

#include <array>
#include <iostream>

using namespace std;

constexpr int MUL(int a, int b) {
    return a * b;
}

int main(int argc, const char * argv[]) {
    array<int, MUL(5, 5)> a;
    printf("size of a = %d\n", (int)a.size()); // size of a = 25

    int b = 5;
    b += 5;

    // array
      
        c; // The left statement will fail to compile because MUL(b, b) cannot determine the result at compile time
      ,>

    const int c = 6;
    array<int, MUL(c, c)> d;
    printf("size of d = %d\n", (int)d.size()); // size of d = 36

    return 0;
}
Copy the code

Array

c; array

c; array

c; array

c; Statement compilation failed.
,>
,>
,>
,>


Interested in mobile development partners can add my public account “Fenghai Tonggong”.