简体   繁体   中英

MS Visual Studio Error: Expected Constant Expression

Take the following code.

#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;
}

My Codeblock compiler is fine with the array allocation, but Microsoft visual studio says that line expects a constant expression.

I understand the difference between stack and dynamic allocation from heap. But In this instance, the parameter len is determined statically anyway, at the compile time. I store the value in a variable (instead of directly using 5) only because my test cases use different len each time I run the program.

So is there any way to make visual studio work with it? Or should I resort to dynamic allocation, even though CodeBlock accepts it?

int arr[len];

len is not a compile time constant expression (it needs to be computed with power function, after all).

C ( as opposed to C++ ) allows for arrays whose length is not know until runtime. Those are called "variable length arrays" (VLAs).

As such, your code is not valid C++. It works with GCC because that compiler (by default) extends C++ with some additional "features", VLAs being one of them.


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

No, it is initialised to the return value of the power function. C++ (by default) does not allow for "super compilation" (executing arbitrary amount of code which is deemed to have a constant result), thus the function can only be called at runtime.

Starting with C++11 there's the constexpr keyword which allows you to mark certain (restricted) functions such that they will be executed during complie time when their parameters are compile time constants.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM