C ++, array size must be const expression

I am currently reading the book "C ++ Primer" by Lappman. On page 113 it says:

The number of elements in an array is part of the array type. As a result, the dimension must be known at compile time, which means that the dimension must be a constant expression.

Also, he says that we cannot do something like this

unsigned cnt  = 43; //not an const expression
string bad[cnt]; // error

      

But it is not, I compiled it without any problem, I can even do something like this

int i;
cin >> i;
get_size(i);

void get_size(int size) {
  int arr[size];
  cout << sizeof (arr);
}

      

And it works well. So why does every book say that the size of an array must be known at compile time? Or should it be a const expression?

+3


source to share


2 answers


Because these books teach you C ++.

This is true in C ++.



What you are using is a non-standard extension provided by GCC specifically called variable length array.

If you include all the warnings from your compiler that you should always do, you will be informed about this at build time.

+6


source


This is known as VLA (Variable Length Arrays). And this is not very acceptable and infact standard in C99 . GCC permits this as an extension of C ++ code.

If you want to experiment, you can use the -std=standard

, -ansi

and options -pedantic

.



You can also refer to Why does the C / C ++ compiler need to know the size of an array at compile time? where the accepted answer has a good explanation on this.

+1


source







All Articles