1

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?

mada
  • 1,646
  • 1
  • 15

1 Answers1

2

In your particular example, the compiler can possibly know. It just doesn't have to.

But what if you have

int x { 10 };
someclass trix{};
constexpr int y { x }; //error: x should be const

Now the constructor for trix just could modify x, and the compiler wouldn't know. Especially if trix.cpp is compiled after the main file.

BoP
  • 2,310
  • 1
  • 15
  • 24