Consider the following code:
static constexpr int make_const(const int i){
return i;
}
void t1(const int i)
{
constexpr int ii = make_const(i); //
Because t1() is not a constexpr function, the parameter i is a runtime variable... which you can't pass to a constexpr function. Constexpr expects the parameter to be known at compile time.
One important difference between const
and constexpr
is that a constexpr
can be evaluated at compile time.
By writing constexpr int ii = make_const(i);
you are telling the compiler that the expression is to be evaluted at compile time. Since i
is evaluted at run-time, the compiler is unable to do this and gives you an error.
A constexpr
function and a constexpr
variable are related, but different things.
A constexpr
variable is a variable whose value is guaranteed to be available at compile time.
A constexpr
function is a function that, if evaluated with constexpr
arguments, and behaves "properly" during its execution, will be evaluated at compile time.
If you pass a non-constexpr
int
to a constexpr
function, it will not magically make it evaluated at compile time. It will, however, be allowed to pass the constexpr
ness of its input parameters through itself (normal functions cannot do this).
constexpr
on functions is a mixture of documentation and restriction on how they are written and instructions to the compiler.
The reason behind this is to allow the same function to be evaluated both at compile time, and at run time. If passed runtime arguments, it is a runtime function. If passed constexpr
arguments, it may be evaluated at compile time (and will be if used in certain contexts).