VS2008 error expected constant expression on declaring array, but no error for this code in GCC

arrays, c++, constants, visual-c++, visual-studio-2008

Solution

`size` is not a constant expression. The term "constant expression" in the error message refers to the C++ concept of Integral Constant Expression. The whole idea of Integral Constant Expression is that its value should be known at compile time. For example, an integral `const` object declared with an initializer can be used as an Integral Constant Expression.

Just because you declared some `int` variable `const` does not turn it into an Integral Constant Expression. Function parameters never form Integral Constant Expressions. This is why you cannot use your `size` to define array size in C++.

GCC compiles your code because it brings over a C-specific feature from C language to C++ as a non-standard extension. Note that in GCC your `size` is not considered constant either. GCC simply does not require array sizes to be constant.

If you switch your GCC compiler into strict and pedantic C++ mode, it will refuse to compile your code just as MSVC++ does.

Problem

I have following function ``` void someFun(int* ar, const int size) { int newAr[size]; //do something } ``` And I get for this line three errors: ``` Error 1 error C2057: expected constant expression Error 2 error C2466: cannot allocate an array of constant size 0 Error 3 error C2133: 'newAr' : unknown size ``` But var size is constant! And using gcc this is compiled without errors. Can you tell me what and why is wrong here for vs2008(or for Visual C++ in general maybe)? Thanks in advance.

Original source