Muru
Muru

Reputation: 103

Is it possible to specify a variable as size specifier for a statically allocated integer array?

I'm surprised that this code compiles and works perfectly without throwing any errors!

int arraysize = 1000;
int array[arraysize];
for(int i=0; i<arraysize; i++)
{
    array[i] = i+1;
}

for(int i=0; i<arraysize; i++)
{
    cout << array[i];
}

Edit: Compiler used: i386-linux-gnueabi-g++ (Linaro GCC 4.5-2012.01) 4.5.4 20120105 (prerelease)

Upvotes: 0

Views: 114

Answers (2)

user1071136
user1071136

Reputation: 15725

This is probably a feature of your compiler (GCC ?) which allows C99 variable-length arrays. In C99, it's valid to define arrays such as

int n;
scanf("%d", &n);
int array[n];

C++ does not, by standard, support variable-length arrays, probably because it has better alternatives, namely std::vector<>. Try compiling with g++ -pedantic-errors file.cpp and you'll receive

error: ISO C++ forbids variable-size array ‘array’

It should be noted that variable-length arrays do not support C++ classes, which is another reason not to bother with them in C++, and instead using std::vector<>.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254461

In C++ the size of an array must be a constant. If you were to declare the size variable const, then it could be used.

C allows variable-length arrays (sometimes called VLAs), and some C++ compilers provide these as an extension; that would be why your code works.

Usually, std::vector is a safer and more portable alternative if you need a dynamically-sized array.

Upvotes: 1

Related Questions