constexpr is new keyword in c++11 and it is used with data type(either build in or user defined) and function. It defines that this value is constant and evaluated during compilation. In other word, it has two functionalities:
- Make the variable or object const (Must be initialised otherwise get compilation error)
- Evaluate the function at compile time.
Source code with example:
//Header File #include<iostream> #include<array> //constexpr function constexpr int sq(int x) { return(x*x);} int main() { std::cout<<"In constexpr"<<std::endl; //constexpr int sz; //constexpr must be instailized //other wise we will get error: uninitialized const ‘sz’ constexpr int sz = 5; //const functionality //std::array std::array<int, sz> arr1; //calling function with constexpr std::array<int, sq(5)> arr2; //evaluation at compile time std::cout<<"size:"<<sizeof(arr2)<<std::endl; //get 100 = 25*4(int size) return 0; }
Output:
In constexpr size:100