1

If I have a variable declared with storage ie int x; and initialize it with a call to a constexpr function will it have the value determined before any code in main starts executing.

constexpr int get_value() { return 5;}

int x = get_value();

int main() {
   return x;
};
Blair Davidson
  • 901
  • 12
  • 35
  • 1
    Its about constexpr. Is the other question about that. – Blair Davidson Mar 11 '19 at 13:29
  • @BlairDavidson: How would `constexpr` change anything? – Nicol Bolas Mar 11 '19 at 13:30
  • @BlairDavidson `constexpr` for functions only means "there is at least one set of arguments where compile-time evaluation is possible". In any case, the answers to the linked question clearly indicate that the initialization happens before `main`. – Max Langhof Mar 11 '19 at 13:32
  • up to you if you want to remove it. – Blair Davidson Mar 11 '19 at 13:34
  • @BlairDavidson **A:Yes** / [Constant initialization](https://eel.is/c++draft/basic.start.static#2) happens because: **1**. `x` is a variable with static storage duration; **2**. the full-expression of its initialization `get_value()` is a [core constant expression](https://eel.is/c++draft/expr.const#5). And it happens [as a consequence of program initiation](https://eel.is/c++draft/basic.start.static#1) which is before program execution. **BTW**, since this question itself is much more than just "Storage Duration", it has its own value and I don't think this question should be closed either. – Michael Lee Dec 29 '21 at 09:16

1 Answers1

1

In C++20, you have constinit for that:

constexpr int get_value() { return 5;}

// Still mutable, not constexpr but
// initialized with a value at compile time.
constinit int x = get_value();

int main() {
   return x;
};
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141