views:

2257

answers:

4

I've been using C++ for a few years, and today I don't know if this is a mere brainfart or what, but how can this be perfectly legal:

int main(int argc, char **argv)
{
    size_t size;
    cin >> size;
    int array[size];
    for(size_t i = 0; i < size; i++)
    {
        array[i] = i;
        cout << i << endl;
    }

    return 0;
}

Compiled under GCC. How can the size be determined at run-time without new or malloc? Just to double check, I've googled some and all similar codes to mine are claimed to give storage size error. Even Deitel's C++ How To Program p. 261 states under Common Programming Error 4.5: Only constants can be used to declare the size of automatic and static arrays.

Enlight me.

+12  A: 

This is valid in C99.

C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too.

Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap allocation is done. It's pretty much like _alloca.

Mehrdad Afshari
+5  A: 

It is valid only in C99. Next time you may try checking your code in a reliable compiler.

Comptrol
+2  A: 

It is valid C99, it is not valid C++. This is one of not a few differences between the two languages.

anon
I guess it's going to be supported in C++0x
Mehrdad Afshari
Not according to section 8.3.4 of the draft standard.
anon
it won't ever be included in c++1x :D but let's hope dynarray<T> gets in. i would love it. so you could do dynarray<int> a(some_size); and have it allocate efficiently, possibly with compiler hax like _alloca and so on.
Johannes Schaub - litb
+6  A: 

This is known as VLAs (variable length arrays). It is standard in c99, but gcc allows it in c++ code as an extension. If you want it to reject the code, try experimenting with -std=standard, -ansi and -pedantic options.

jpalecek