Reputation: 15621
There is such code:
#include <iostream>
int main()
{
int size;
std::cin >> size;
size = size + 1;
int tab3[size];
tab3[0] = 5;
std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
return 0;
}
The result is:
$ g++ prog.cpp -o prog -Wall -W
$ ./prog
5
5 24
Why does this code even compile? Shouldn't be length of array a constant variable?
I used g++ version 4.4.5.
Upvotes: 10
Views: 792
Reputation: 7985
It is a C99 feature, not a part of C++. They are commonly refered to as VLAs(Variable Length Arrays.
If you run g++
with -pedantic
it will be rejected.
See GCC docs for more info.
See also: VLAs are evil.
Upvotes: 7
Reputation: 1814
GCC provide's VLA's or variable length arrays. A better practice is to create a pointer and use the new
keyword to allocate space. VLA's are not available in MSVC, so the second option is better for cross platform code
Upvotes: 2
Reputation: 476960
Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic
).
Upvotes: 13