问题
I recently found a interesting behaviour of g++ when compared with MSVC++ 2008. Consider this tiny program:
#include <cstdlib>
const int ARR_LENGTH = 512;
void doSomething( int iLen );
int main( int argc, char** argv )
{
doSomething( ARR_LENGTH );
return 0;
}
void doSomething( int iLen )
{
int iTest[iLen];
return;
}
Will it compile? What do you think? According to my knowledge of C (or C++ for that matter), this should NOT compile, since i can call the function doSomething() with any integer i want, so the size of iTest array cannot be determined at compile time. However, when i try to compile this with g++, it works just fine. Now i can understand what probably happened here - the compiler noticed that i call this function only once passing a compile-time constant as a parameter. Some serious optimizations going on here... But when i try to compile this using MSVC++ 2008, i get this:
1>c:\prj\test\test.cpp(15) : error C2057: expected constant expression
1>c:\prj\test\test.cpp(15) : error C2466: cannot allocate an array of constant size 0
1>c:\prj\test\test.cpp(15) : error C2133: 'iTest' : unknown size
My question is: how does this comply with the definition of the language (the C standard (C++ standard))? Is it just fine for g++ to do such an optimization (which in this case is easy to see, but the first time i encountered it, it was in a large project and it did not make much sense at first sight).
回答1:
C99 (the most recent version of the C standard) does allow dynamically sized arrays. However, the feature is not supported by Visual Studio (which only implements C89 support)
In C++ it is not, and probably will never be, valid.
回答2:
Dynamically sized arrays are a feature of C99. If your compiler supports C99 (GCC does, VC doesn't fully) - and if you throw the C99 switch -, then this will compile.
回答3:
This is not standard C++ (but standard C). Implementations may provide alloca (or _alloca with msvc) which pretty much does the job.
来源:https://stackoverflow.com/questions/3093049/different-behavior-of-compilers-with-array-allocation