A constexpr
variable is used when its value is supposed to be constant throughout a program’s execution. The constexpr
keyword computes the value of such a variable during compilation, and the compiler looks to see if it can detect any changes to that variable.
A constexpr
array can be declared and initialized manually through:
constexpr int arr[3] = {1,2,3};
However, manually initializing a large array can become tiresome.
For example, to initialize an integer array of size , with integers from to , a struct is declared that has an int
array. This array is then initialized using a constexpr
constructor.
A template with non-type parameters has been used in the code below to declare an array of a particular size.
#include <iostream>using namespace std;template<int size>struct ConstArray{int arr[size];// 'constexpr' constructor:constexpr ConstArray():arr(){for(int i = 0; i < size; i++)arr[i] = i;}// This member function should have 'const':void print() const{for(int i = 0; i < size; i++)cout << arr[i] << endl;}};int main() {constexpr int n = 5;constexpr ConstArray arr = ConstArray<n>();arr.print();return 0;}
Free Resources