82

I've been using C++ for a few years, and today I saw some code, 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.

cigien
  • 57,834
  • 11
  • 73
  • 112
syaz
  • 2,659
  • 6
  • 36
  • 44

8 Answers8

74

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.

Benny K
  • 868
  • 6
  • 18
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 14
    I came across this same scenario in a file in our code base that was written months ago. I was baffled, as was the rest of the team, as to why it compiled. In our situation, the size of the array was calculated before declaring the array as well (which shouldn't be allowed, either?) Anyway, a challenge went out. Anyone who could answer why this is legal gets a pop tart. If you're ever in Seattle, let me know. I have a pop tart for you. – Jeff Lamb Jan 12 '11 at 22:55
  • 2
    Can you provide some info/link on how stack internally works in this case? Does this introduce some overhead in run time? – balki Jul 06 '11 at 11:21
  • 2
    @balki The overhead is minor, as it's basically increment/decrementing the stack pointer. The stack behavior can be essentially identical to the normal case if you save the original stack pointer at the beginning of the function. – Mehrdad Afshari Jul 06 '11 at 19:31
  • is this allowed in c++ ? Visual studio does not allow this? – justpraveen Jan 10 '15 at 16:22
  • What I don't get is that when assembler generates the assembly code, it does not know the exact size of array at that time. So how much offset it is going to move the stack pointer to make room for this dynamic-sized array? It can't tell. So it is pretty interesting to know how this is implemented – torez233 Dec 05 '22 at 04:35
26

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
  • 47,058
  • 7
  • 102
  • 144
6

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

Özgür
  • 8,077
  • 2
  • 68
  • 66
5

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

1

This Code runs in GNU GCC Compiler.

#include<bits/stdc++.h>

int main(int argc, char **argv)

{
    size_t size;

   std:: cin >> size;

    int array[size];

    for(size_t i = 0; i < size; i++)

{

array[i] = i;

        std:: cout << i;

 }

    return 0;
}
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
Dungeon
  • 11
  • 1
0

You can give size to an array dynamically in if you are using Dev-Cpp compiler I have tried it and got no error but on visual c++ and visual studio compilers it is not possible. I think the reason is that dev-c++ assigns a positive number to the uninitialized int and when we give it a number it is replaced by the given one. but perhaps other compilers give null to uninitialized variables.

Najeeb
  • 1
  • Most compilers don't assign anything to uninitialized local variables, they will usually appear to hold whatever was in the memory that they occupy until they are assigned by the program. It seems the Dev-C++ you referenced is an IDE on top of MinGW, which includes a port of GCC as the compiler. As noted in other answers, VLAs are not standard C++, but some compilers (including g++) support them anyway. – jerry May 22 '13 at 13:27
  • Dev-C++ is not a compiler. Neither is Visual Studio. Dev-C++ uses GCC/G++ as its compiler, while Visual Studio uses cl (Microsoft's compiler back-end). By themselves, Dev-C++ and Visual Studio are Integrated Development Environments (IDEs). This is an important distinction to make. Dev-C++ does not "assign" anything. The compiler does that. – Elkvis Oct 13 '14 at 14:35
0

I recently came across a scenario where a stack-allocated array is desired. (It's a wrapper around v8, needed an array of args on every method call).

An std::vector would do heap memory allocation, whose performance is not acceptable.

Here is my solution, use template to allocation array of cases:

template<size_t Argc>
static void call(...) {
    v8::Local<v8::Value> v8Args[Argc];

    // use v8Args
    ...
}

template<typename It>
static void callV8Function(size_t argc, It argvBegin, It argvEnd,) {
    // C++ don't have dynamic stack allocation (like C99 does)
    // try to avoid heap-allocation...
    if (argc <= 4) {
        return callV8FunctionOnStack<4>(...);
    } else if (argc <= 8) {
        return callV8FunctionOnStack<8>(...);
    } else if (argc <= 16) {
        return callV8FunctionOnStack<16>(...);
    } else if (argc <= 32) {
        return callV8FunctionOnStack< 32>(...);
    } else {
        std::vector<v8::Local<v8::Value>> v8Args(argc);
        // fallback to vector
   }
}

(And of course, I can just do with a 32-sized array, but which is not so elegant.)

landerlyoung
  • 1,693
  • 17
  • 14
-1

Variable Length Arrays (VLAs) are supported in the C++14 standard, which has recently been accepted, and is awaiting publication.

Elkvis
  • 728
  • 1
  • 5
  • 21
  • 2
    VLAs are still not part of the standard. There's a [dynarray](http://en.cppreference.com/w/cpp/container/dynarray) TS, but as of yet it isn't ratified. – Jason Nov 18 '15 at 23:24