PeterK
PeterK

Reputation: 6317

Different behavior of compilers with array allocation

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

Upvotes: 6

Views: 200

Answers (3)

Alexandre C.
Alexandre C.

Reputation: 56956

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

Upvotes: 0

sbi
sbi

Reputation: 224079

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.

Upvotes: 2

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247979

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.

Upvotes: 5

Related Questions