Declaring the array size with a non-constant varia

2019-01-04 01:17发布

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 :

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

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

I got no error ! I'm using GCC v4.4.0.

Is there something I'm missing ?

标签: c++ arrays gcc
3条回答
Fickle 薄情
2楼-- · 2019-01-04 02:02

This is a GCC extension to the standard: see here.

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).

查看更多
Ridiculous、
3楼-- · 2019-01-04 02:07

You also can use the function alloca to get an effect much like variable-length arrays. It is available on VS too.

alloca - allocate memory that is automatically freed. The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller. The alloca() function is machine- and compiler-dependent. For certain applications, its use can improve efficiency compared to the use of malloc(3) plus free(3).

查看更多
唯我独甜
4楼-- · 2019-01-04 02:13

You are using a feature from C99 which is called VLA(variable length arrays). It would be better if you compile your program like this:

g++ -Wall -std=c++98 myprog.cpp
查看更多
登录 后发表回答