Understanding constexpr Specifier in C++

03 Jun, 2022
constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template metaprogramming).  constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions. 
Example:
CPP
// C++ program to demonstrate constexpr function for product// of two numbers. By specifying constexpr, we suggest// compiler to to evaluate value at compile time#include <iostream>  constexpr int product(int x, int y) { return (x * y); }  int main(){    constexpr int x = product(10, 20);    std::cout << x;    return 0;}
Output :
200
A function be declared as constexpr
In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.constexpr function should refer only to constant global variables.constexpr function can call only other constexpr function not simple function.The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function.
In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.
constexpr function should refer only to constant global variables.
constexpr function can call only other constexpr function not simple function.
The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function.
Constexpr
Inline Functions
Example of performance improvement by constexpr: 
CPP
// A C++ program to demonstrate the use of constexpr #include<iostream> using namespace std;   constexpr long int fib(int n) {     return (n <= 1)? n : fib(n-1) + fib(n-2); }   int main () {     // value of res is computed at compile time.     constexpr long int res = fib(30);     cout << res;     return 0; } 
Output:
832040
When the above program is run on GCC, it takes 0.003 seconds (We can measure time using the time command) If we remove const from the below line, then the value of fib(5) is not evaluated at compile-time, because the result of constexpr is not used in a const expression.
Change,
  const long int res = fib(30);  
To,
  long int res = fib(30);
After making the above change, the time taken by the program becomes higher by 0.017 seconds.
constexpr with constructors: A constructor that is declared with a constexpr specifier is a constexpr constructor also constexpr can be used in the making of constructors and objects. A constexpr constructor is implicitly inline.
Restrictions on constructors that can use constexpr:
No virtual base class
Each parameter should be literal
It is not a try block function
Example:
CPP
// C++ program to demonstrate uses // of constexpr in constructor #include <bits/stdc++.h> using namespace std;   // A class with constexpr // constructor and function class Rectangle {     int _h, _w; public:     // A constexpr constructor     constexpr Rectangle (int h, int w) : _h(h), _w(w) {}           constexpr int getArea () { return _h * _w; } };   // driver program to test function int main() {     // Below object is initialized at compile time     constexpr Rectangle obj(10, 20);     cout << obj.getArea();     return 0; } 
Output :
200
They serve different purposes. constexpr is mainly for optimization while const is for practically const objects like the value of Pi. Both of them can be applied to member methods. Member methods are made const to make sure that there are no accidental changes in the method. On the other hand, the idea of using constexpr is to compute expressions at compile time so that time can be saved when the code is run. const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types. 
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Shun Xian Cai
nidhi_biet
preethibr1
mahdiarfaoui5477
harsh_shokeen
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL