In C++, I know that if a I declared a variable inside a function, this variable is actually considered as auto
local variable (destroyed once a function does return
). So it stands to reason that, a local variable cannot appears in a constant expression like an initializer for a constexpr
variable, because simply it known at runtime, it needs the function in which it declared to be executed and that's happening only at runtime.
int x { 10 };
constexpr int y { x }; //error: x should be const
int main()
{
//..
}
My question is, what would happen if this variable is global? So no runtime functions need to be executed in order to know the value of x
, because it does not belong to any functions? My question, in other words, when does exactly the compiler knows the value of this variable x
I already know that, if the variable x
is const, then x
will be a constant expression but why is that?