MS Visual Studio Error: Expected Constant Expression

MS Visual Studio Error: Expected Constant Expression

取下面的代码。

#include "iostream"
using namespace std;
unsigned power(unsigned b, unsigned e){return e?b*power(b, e-1):1;}//Raises base b to a power e
int main(int argc, char* argv[])
{const unsigned lev=5, len=power(2, lev)-1;
int arr[len]; //Error according to Microsoft visual studio
cout<<"The code worked."<<endl;
}

我的 Codeblock 编译器适用于数组分配,但 Microsoft visual studio 表示该行需要常量表达式。

我了解堆栈和堆动态分配之间的区别。但是在这种情况下,参数 len 无论如何都是在编译时静态确定的。我将值存储在一个变量中(而不是直接使用 5)只是因为每次我 运行 程序时我的测试用例使用不同的 len

那么有什么方法可以让 visual studio 使用它吗?或者我应该求助于动态分配,即使 CodeBlock 接受它?

int arr[len];

len不是编译时常量表达式(毕竟需要用power函数计算)。

C(相对于 C++)允许数组的长度直到运行时才知道。这些被称为 "variable length arrays" (VLA)。

因此,您的代码不是有效的 C++。它适用于 GCC,因为该编译器(默认情况下)通过一些额外的 "features" 扩展了 C++,VLA 就是其中之一。


But In this instance, the parameter len is determined statically anyway, at the compile time.

不是,它被初始化为power函数的return值。 C++(默认情况下)不允许 "super compilation"(执行任意数量的被认为具有常量结果的代码),因此该函数只能在运行时调用。

从 C++11 开始,有 constexpr 关键字,它允许您标记某些(受限)函数,以便当它们的参数是编译时间常量时,它们将在编译期间执行。