In this particular example the local variables would be best declared constexpr
, not const
, because they can be computed at compile time:
constexpr int g() { return 30; }
constexpr int f()
{
constexpr int x = g();
constexpr int y = 10;
return x + y;
}
When f()
is called at run time, without the constexpr
on x
and y
, (with or without the const
on x
and y
) you are giving the compiler the option to initialize x
and y
at run time instead of compile time. With the constexpr
on x
and y
, the compiler shall compute x
and y
at compile time, even when f()
is executed at run time.
In a different function however, constexpr
can't always be used. For example if f()
and g()
took a parameter:
constexpr int g(int z) { return z+30; }
constexpr int f(int z)
{
const int x = g(z);
constexpr int y = 10;
return x + y;
}
Now x
can not be marked constexpr
because z
may not be a compile-time constant, and there is currently no way to mark it as such. So in this case, marking x
const
is the best you can do.