views:

80

answers:

3

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).

+5  A: 

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.

jalf
Why will it never be valid in C++? The compiler just has to adjust the stack pointer, initialize everything with the default constructor, and make sure that it gets cleaned up on scope exit, right? Not easy, but not impossible, either. It sure beats using `alloca()`.
Mike DeSimone
Jalf said "probably never will be valid", and a good reason to think that is that the C++ committee just finished writing the standard for the next version of C++, they definitely considered all the features that C added in C99, and VLAs weren't accepted. See also http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c
Ben Voigt
As @Ben said, it was rejected for the upcoming C++0x, so they'd have to reverse that decision in order to add it later. And it's just not as necessary in C++ as it was in C. C++ already has `std::vector` which solves many of the same problems. There's just less of a need for VLAs in C++.
jalf
+2  A: 

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.

sbi
A: 

This is not standard C++ (but standard C). Implementations may provide alloca (or _alloca with msvc) which pretty much does the job.

Alexandre C.