Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array allocation in C++ on stack with varying length [duplicate]

I was surprised to find out that it is possible to allocate an varying-length array on the stack in C++ (such as int array[i];). It seems to work fine on both clang and gcc (on OS/X) but MSVC 2012 don't allow it.

What is this language feature called? And is it an official C++ language feature? If yes, which version of C++?

Full example:

#include <iostream>

using namespace std;

int sum(int *array, int length){
    int s = 0;
    for (int i=0;i<length;i++){
        s+= array[i];
    }
    return s;
}

int func(int i){
    int array[i]; // <-- This is the feature that I'm talking about
    for (int j=0;j<i;j++){
        array[j] = j;
    }

    return sum(array, i);

}

int main(int argc, const char * argv[])
{
    cout << "Func 1 "<<func(1)<<endl;
    cout << "Func 2 "<<func(2)<<endl;
    cout << "Func 3 "<<func(3)<<endl;

    return 0;
}
like image 395
Mortennobel Avatar asked Nov 23 '25 08:11

Mortennobel


2 Answers

You're looking at GCC's variable length arrays. That's a GNU extension and is not standard C++.

like image 59
DUman Avatar answered Nov 25 '25 23:11

DUman


This feature is called Variable Length Arrays or VLAs.

It's part of C99 standard (and also C11) but is not supported by C++11. However, as you see some compilers accept it as an extension.

Finally, a similar feature (but not exactly the same as C99's VLAs) was approved at the C++ committee meeting in Bristol (April 2013) and is in the current draft of C++14.

Two main differences between C99's VLAs and C++14's are illustrated below:

void f(std::size_t n) {
    int a[n];
    unsigned int x = sizeof(a);
    // ...
    int matrix m[n][n];
}    

In C99, the expression sizeof(a) is evaluated at runtime. In C++14 this is illegal. In addition, multidimensional VLAs are not supported by C++14.

For more information on C99's VLAs see this DrDobb's article.

For more information on C++14's runtime-sized arrays see N3639, the paper that was approved in Bristol.

Update: In the Chigago meeting, the committee decided to remove this feature from C++14 and instead put it in a separate document, a Technical Specification (TS) on array Extendions (TS). In addition, the TS also includes the template class dynarray which is somewhat related to arrays of runtime bounds.

The main reason it was dropped from C++14 is that the committee wants to get feedback from implementation and user experience before standardizing these features.

like image 22
Cassio Neri Avatar answered Nov 26 '25 00:11

Cassio Neri