0

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)

tshepang
  • 12,111
  • 21
  • 91
  • 136
Muru
  • 93
  • 1
  • 1
  • 7

2 Answers2

1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

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

user1071136
  • 15,636
  • 4
  • 42
  • 61
  • VLAs are really hard to make consistent with the C++ object model. What if there's an exception in a constructor of one of the elements, for example? – Kerrek SB Sep 05 '12 at 10:15