constexpr (C++) | Microsoft Docs
Understanding constexpr specifier in C++ - GeeksforGeeks
constexpr is a feature added in C++11. The main idea is performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time
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. For example, in below code product() is evaluated at compile time.
constexpr int product(int x, int y)
{
return (x*y);
}
int main()
{
const int x = product(10, 20);
cout << x;
return 0;
}
output: 20
A function be declared as constexpr
1. In C++11, a constexpr function should contain only one return statement. C++14 allows more than one statements.
2. constexpr function should refer only constant global variables.
3. constexpr function can call only other constexpr function not simple function.
4. Function should not be of void type and some operator like prefix increment(++v) are not allowed in constexpr function.
constexpr vs inline functions:
Both are for performance improvments, inline functions request compiler to expand at compile time and save time of function call overheads. In inline functions, expression are always evaluated at run time. constexpr is different, here expressions are evaluated at compile time.
#include <iostream>
using namespace std;
constexpr long int fib(int n)
{
return (n <= 1)? n : fib(n-1) + fib(n-2);
}
int main()
{
const long int res = fib(30);
cout << res;
return 0;
}
constexpr with constructors:
#include <bits/stdc++.h>
using namespace std;
class Rectangle
{
int _h, _w;
public:
constexpr Rectangle(int h, int w): _h(h), _w(w) {}
constexpr int getArea() { return _h * _w;}
};
int main()
{
constexpr Rectange obj(10, 20);
cout << obj.getArea();
return 0;
}
constexpr vs const
They serve different purposes. constexpr is mainly for optimaization while const is for pratically const objects like value of Pi.
Both of them can be applied to member methods. Member methods are made const to make sure that there are no accident changes by the method. On the other hand, the idea of using consexpr is to compute expressions at compile time so that time can be saved when code is run.
const can only be used with non-static member function 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.