Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring the array size with a non-constant variable

Tags:

c++

arrays

gcc

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?

like image 343
Jérôme Avatar asked May 19 '10 06:05

Jérôme


People also ask

How do you declare an array with variable size?

Variably changed types must be declared at either block scope or function prototype scope. Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.

How do you declare an array When size is not known?

You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.

Can we declare array size?

You can declare one-dimensional (1D) arrays with any non-negative size. int [] arr = new int[ 10 ]; // Array of size 10 int [] arr2 = new int[ 100 ]; // Array of size 100 int [] arr3 = new int[ 1 ]; // Array of size 1 int [] arr4 = new int[ 0 ]; // Array of size 0!

Can you initialize array with variable size?

But, unlike the normal arrays, variable sized arrays cannot be initialized.


2 Answers

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

like image 154
Dean Harding Avatar answered Sep 28 '22 05:09

Dean Harding


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 
like image 22
Khaled Alshaya Avatar answered Sep 28 '22 06:09

Khaled Alshaya