The code below should generate an error, since there is no way that the compiler can know the array size during compilation.
int f;
std::cin >> f;
int c[f];
c[100] = 5;
I am compiling with gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2 and it doesn't just compile, but it runs somehow.
How does it happen?
In C++, the compiler must know the amount of memory to allocate for an array at compile time. However, the value of a variable is not known until run time. This is why you are not allowed to use a variable for the size of an array.
You can define variable-size arrays by: Using constructors, such as zeros , with a nonconstant dimension. Assigning multiple, constant sizes to the same variable before using it. Declaring all instances of a variable to be variable-size by using coder.
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself: int n = 10; double* a = new double[n]; // Don't forget to delete [] a; when you're done!
C99 accepts variable length arrays, and gcc accepts them as an extension in C90 and C++.
Using -pedantic
or -Wvla
turns this into a warning in C++ code, and -Werror=vla
turns it into an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With