Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c++ - Declaring the array size with a non-constant variable

I always thought that when declaring an array in C++, the size has to be a constant integer value.

For instance:

int MyArray[5]; // correct

or

const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct

but

int ArraySize = 5;
int MyArray[ArraySize]; // incorrect

Here is also what is explained in The C++ Programming Language, by Bjarne Stroustrup:

The number of elements of the array, the array bound, must be a constant expression (§C.5). If you need variable bounds, use a vector(§3.7.1, §16.3). For example:

  void f(int i) {
      int v1[i];          // error : array size not a constant expression
      vector<int> v2(i);  // ok
  }

But to my big surprise, the code above does compile fine on my system!

Here is what I tried to compile using GCC v4.4.0:

void f(int i) {
    int v2[i];
}

int main() {
    int i = 3;
    int v1[i];
    f(5);
}

Success?!?

Is there something I'm missing?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a GCC extension to the standard:

You can use the -pedantic option to cause GCC to issue a warning, or -std=c++98 to make in an error, when you use one of these extensions (in case portability is a concern).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...