0

I'm a beginner in C++. I had seen one sample code as shown below:

int quantity;
cout << "Enter the number of items: " << endl;
cin >> quantity;
int *arr = new int[quantity];

for(int i=0; i <quantity; i++)
{ 
cout<< "Enter item no." << i << endl;
cin >> arr[i];
}

But when I replaced the int *arr = new int[quantity]; with int arr[quantity];, the program can still be compiled without any error messages. Why is int *arr = new int[quantity] used instead of int arr[quantity]?

Melebius
  • 6,183
  • 4
  • 39
  • 52
Autumn
  • 105
  • 1
  • 1
  • 7

1 Answers1

3

quantity is not a compile-time constant, so the following:

int arr[quantity];

...is not valid C++ (even though it is valid C99).

Your code probably compiles because your compiler as an extension allowing this construct, such as GCC VLA extension:

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++.

Compiling with -pedantic should give you at least a warning. GCC gives me the following (with -pedantic):

8 : :8:21: warning: ISO C++ forbids variable length array 'arr' [-Wvla]

int arr[quantity];

Note that in this case, you should probably be using a std::vector and not a manually allocated array:

std::vector<int> arr(quantity);
Holt
  • 36,600
  • 7
  • 92
  • 139