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?

2
  • @juan: If using Stack Overflow, try the answer section to post an answer to a question. Commented May 28, 2015 at 6:59
  • @LightnessRacesinOrbit I was picking a suitable duplicate. Difficult to choose when there are so many. Commented May 28, 2015 at 7:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

It's discouraged in C++, though. Highly unportable and unnecessary.
@LightnessRacesinOrbit:- Yes thats correct, thats why I added the C99 part.
I'm just saying this is a bit misleading. You could emphasise that it's not "very much acceptable and in fact standard" as far as this question goes.
@LightnessRacesinOrbit:- Updated that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.