Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this code generate an error on using a variable array size?

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?

like image 566
v010dya Avatar asked Apr 08 '15 07:04

v010dya


People also ask

Why array size should not be a variable?

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.

Can you declare an array with a variable size?

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.

Why are variable length arrays bad?

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.

How do you make a variable size array in C++?

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!


1 Answers

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.

like image 79
BoBTFish Avatar answered Sep 22 '22 13:09

BoBTFish