static constexpr vs constexpr in function body?
Is there any difference between static constexpr
and constexpr
when used inside a function's body?
int SomeClass::get(const bool b)
{
static constexpr int SOME_CONSTANT = 3;
constexpr int SOME_OTHER_CONSTANT = 5;
if(b)
return SOME_CONSTANT;
else
return SOME_OTHER_CONSTANT;
}
The main difference between those two declarations is the lifetime of the objects. When writing the question, I thought that using constexpr
instead of const
would place that object into the .rodata
section. But, I was wrong. The constexpr
keyword, here, only provides that the object can be used at compile-time functions. So, the object is actually created in the stack during run-time and destroyed when leaving the function's body.
On the other hand, the static constexpr
object is an object placed in the .rodata
section. It is created right before the program begins execution. In addition, thanks to the constexpr
, it is also available during compile-time.