3

I'm currently reading the book "C++ Primer" by Lappman. In page 113 It says

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

In addition it says we can't do something like this

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

But it's not true, I compiled it without any problem, I can do even 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 every book say that array size must be known at compile time? Or it must be const expression?

omidh
  • 2,526
  • 2
  • 20
  • 37

2 Answers2

6

Because those books are teaching you C++.

It is true, in C++.

What you are using is a non-standard extension provided by GCC specifically, called Variable Length Arrays.

If you turn on all your compiler warnings, which you should always do, you will be informed about this during the build.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

These are known as VLAs (variable length arrays), and they are in fact standard in C99, although they are not always considered acceptable and are not required to be supported by the compiler as of C11. GCC allows them as an extension in C++ code.

If you want to do some experimenting then you can use -std=standard, -ansi and -pedantic options.

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

irowe
  • 638
  • 11
  • 21
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331