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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With