关于C#:constexpr初始化全局变量

constexpr initialization of global variable

本问题已经有最佳答案,请猛点这里访问。

如果我有一个用存储声明的变量,即int x;并通过调用constexpr函数对其进行初始化,以使其具有在main中的任何代码开始执行之前确定的值。

1
2
3
4
5
6
7
constexpr int get_value() { return 5;}

int x = get_value();

int main() {
   return x;
};


在C 20中,您为此是constinit

1
2
3
4
5
6
7
8
9
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;
};